Android系统中主要提供了三种方式用于简单地实现数据持久化功能,即文件存储,SharePreference存储以及数据库存储。还能将数据保存到手机的SD卡中,不过比较复杂,安全性也不如前三种方式。接下来就对这三种存储方式进行分别讲解。
1,文件存储
文件存储是Android中最基本的一种数据存储方式,它不对存储的内容作任何的格式化处理,所有数据都是原封不动地保存到文件当中的,比较适合用于存储一些简单的文本数据或者二进制数据。
将输入的数据保存:
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
String inputText = edit.getText().toString();
save(inputText);
}
public void save(String inputText) {
// TODO Auto-generated method stub
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("edit", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if (writer != null){
writer.close();
}
} catch (IOException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
从文件中读取数据:
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit);
String inputText = load();//载入存储的数据
if (!TextUtils.isEmpty(inputText)){
edit.setText(inputText);
edit.setSelection(inputText.length());
Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show();
}
}
private String load() {
// TODO Auto-generated method stub
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("edit");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if (reader != null){
try {
reader.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
return content.toString();
}
对字符进行非空判断时可以使用TextUtils.isEmpty()方法,它能一次性进行两种空值(null或者空字符串)的判断。