持久化技术提供了一种机制可以让数据从内存转换到存储设备中
Android提供了3种方式实现数据持久化功能:文件存储、SharedPreference
存储和数据库存储
Context
类提供了一个openFileOutput()
方法,可以将数据存储到指定的文件。
第一个参数是文件名(不包含路径),第二个参数是文件的操作模式,MODE_PRIVATE
是默认操作模式,表示指定同样文件名时,写入的内容会覆盖原有的内容;MODE_APPEND
表示文件名已存在时追加内容,不存在时创建新文件。
public class MainActivity extends AppCompatActivity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = findViewById(R.id.edit);
}
@Override
protected void onDestroy() {
super.onDestroy();
String s = edit.getText().toString();
save(s);
}
public void save(String s) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
//openFileOutput是ContextWrapper类的方法
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(s);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class MainActivity extends AppCompatActivity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = findViewById(R.id.edit);
String s = load();
//TextUtils.isEmpty()方法可以一次性进行两种空值的判断,传入的字符串等于null或等于空字符串时都会返回true
if(!TextUtils.isEmpty(s)){
edit.setText(s);
//调用setSelection()方法将输入光标移动到文本的末尾位置以便继续输入
edit.setSelection(s.length());
Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show();
}
}
...
private String load(){
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine())!=null){
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder.toString();
}
}
SharedPreference
存储以键值对的方式存储数据
获取Sharedpreferences
对象的三种方法:
Context
类中的getSharedPreferences()
方法:第一个参数指定SharedPreferences
文件的名称,指定的文件不存在则会创建一个,第二个参数指定操作模式,只有MODE_PRIVATE
一种模式可选,表示只有当前的应用程序才可以对这个SharedPreferences
文件进行读写Activity
类中的getPreferences()
方法:只接收一个操作模式参数,因为这个方法会自动将当前活动的类名作为SharedPreferences
的文件名PreferenceManager
类中的getDefaultSharedPreferences()
方法:这是一个静态方法,接收一个Context
参数,自动使用当前应用程序的包名作为前缀来命名Sharedpreferences
文件SharedPreferences
中调用SharedPreferences
对象的edit()
方法获取SharedPreferences.Editor
对象
使用putString()
或putBoolean()
方法向SharedPreferences.Editor
对象添加数据
调用apply()
方法将添加的数据提交
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button save = findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit();
editor.putString("name", "jack");
editor.putInt("age", 28);
editor.putBoolean("married", false);
//提交,完成数据存储操作
editor.apply();
}
});
}
}
SharedPreferences
中读取数据调用SharedPreferences
对象的getString()
,getInt()和getBoolean()
方法,这些get
方法接收两个参数,第一个参数是键,第二个参数是默认值
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Jack";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
Button restore = findViewById(R.id.restore);
restore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences pref = getSharedPreferences("data", Context.MODE_PRIVATE);
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married", false);
Log.d(TAG, "name is " + name);
Log.d(TAG, "name is " + age);
Log.d(TAG, "name is " + married);
}
});
}
}
public class LoginActivity extends BaseAcitvity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
Button login = findViewById(R.id.login);
EditText account = findViewById(R.id.account);
EditText password = findViewById(R.id.password);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
CheckBox rememberPassword = findViewById(R.id.remember_password);
boolean aBoolean = pref.getBoolean("remember_password", false);
if(aBoolean){
String account1 = pref.getString("account", "");
String password1 = pref.getString("password", "");
account.setText(account1);
password.setText(password1);
rememberPassword.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s_acount = account.getText().toString();
String s_password = password.getText().toString();
if ("admin".equals(s_acount) && "123456".equals(s_password)) {
SharedPreferences.Editor editor = pref.edit();
if(rememberPassword.isChecked()){
editor.putString("account",s_acount);
editor.putString("password",s_password);
editor.putBoolean("remember_password",true);
}else {
editor.clear();
}
editor.apply();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}else {
Toast.makeText(LoginActivity.this, "account or password is invalid", Toast.LENGTH_SHORT).show();
}
}
});
}
}