前序:
Android五大存儲:內部存儲、外部存儲、網(wǎng)絡存儲、SharedPreferences和SQLite
? ? ? ?每天都有新的感悟,而能將感悟記錄下來并分享,這成了我目前唯一能堅持的一件事情。這次小編想分享的是Android五大存儲之內部存儲,并將案例整理如下:
正文:
? ? ? ? ?此次案例是:登陸存儲賬號密碼,勾選單選框登陸,下次無需重新輸入賬號密碼可直接登陸。
先看圖:
? ? ? 用手機截圖的,可以看時間,首先進入登陸界面,輸入賬號密碼,選中記住賬號密碼的登陸,退出重新進入賬號密碼已經自動填充。
代碼:
? ?public class MainActivity extends AppCompatActivity {
privateEditTextet_user;//用戶賬號
privateEditTextet_password;//密碼
privateCheckBoxcb;//記住賬號密碼
privateButtonbtn_login;//登陸
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();//初始化
readAccount();//讀取賬號密碼
}
private voidreadAccount() {
File file =newFile("data/data/com.xuchen.logininroom/info.txt");
if(file.exists()){
try{
FileInputStream fileInputStream =newFileInputStream(file);
//將字節(jié)流轉化為字符流
BufferedReader bufferedReader =newBufferedReader(newInputStreamReader(fileInputStream));
//讀取text文件里的用戶名跟密碼
String readLine = bufferedReader.readLine();
String[] split = readLine.split("##");
et_user.setText(split[0]);
et_password.setText(split[1]);
}catch(IOException e) {
e.printStackTrace();
}
}
}
private voidinitView() {
et_user= (EditText) findViewById(R.id.et_user);
et_password= (EditText) findViewById(R.id.et_password);
cb= (CheckBox) findViewById(R.id.cb);
btn_login= (Button) findViewById(R.id.btn_login);
}
//登陸監(jiān)聽
public voidlogin(View view){
//字符串
String user =et_user.getText().toString();
String password =et_password.getText().toString();
//判斷選框是否被選
if(cb.isChecked()){
//內部存儲路徑:data/data/com.xuchen.logininroom
File file =newFile("data/data/com.xuchen.logininroom/info.txt");
try{
FileOutputStream fileOutputStream =newFileOutputStream(file);
fileOutputStream.write((user+"##"+password).getBytes());
fileOutputStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
Toast.makeText(this,"登陸成功",Toast.LENGTH_SHORT).show();
}
布局:
反饋:
CSDN:http://write.blog.csdn.net/postlist
github: https://github.com/ITtrap
QQ: 2632545852
Email: xuchen1009@gmail.com