6.1 持久化技术的简介
什么是数据持久化技术?
将内存中的瞬时数据保存到存储设备中,保证手机在关机的情况下数据仍然不会丢失。
安卓提供了三种方式用于简单的数据持久化功能:文件储存,SharedPreference存储,数据库储存。
6.2 文件存储
用于保存一些简单的文本数据或二进制数据。
使用到的方法:Context类中提供了openFileOutput()方法 和 openFileInput()方法
openFileOutput()方法 拥有两个参数 第一个是文件名 第二个是文件的操作方式
默认的存储到/data/data/<package name> /files目录下
文件的操作方式: MODE_PRIVATE当指定同样文件名时会覆盖原文件中的内容
MODE_APPEND当该文件已存在时就往文件中追加内容,不会创建新文件
文件存储使用:java流
6.2.1 将数据存储到文件中
public void save(String inputText) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
//用于将数据存储到指定的文件中,接收两个参数,
//第一个是文件名,第二个是文件的操作模式
out = openFileOutput("data", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
writer = new BufferedWriter(new OutputStreamWriter(out));
try {
writer.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
}catch(Exception ee){
ee.printStackTrace();
}
}
}
6.2.2 从文件中读取数据
public void save(String inputText) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
//用于将数据存储到指定的文件中,接收两个参数,
//第一个是文件名,第二个是文件的操作模式
out = openFileOutput("data", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
writer = new BufferedWriter(new OutputStreamWriter(out));
try {
writer.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
}catch(Exception ee){
ee.printStackTrace();
}
}
}
6.2.2 从文件中读取数据
public String load() throws IOException {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
/*
只接收一个参数,即要读取的文件名,然后系统会自动到
/data/data/<package name>/file/目录下去加载这个文件
*/
in = openFileInput("data");
//通过java流将数据读取
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null) {
content.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(reader != null) {
reader.close();
}
}
return content.toString();
}
6.3 SharedPreferences存储
public String load() throws IOException {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
/*
只接收一个参数,即要读取的文件名,然后系统会自动到
/data/data/<package name>/file/目录下去加载这个文件
*/
in = openFileInput("data");
//通过java流将数据读取
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null) {
content.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(reader != null) {
reader.close();
}
}
return content.toString();
}
sharedPreferences是采用键值对的方式存储数据的,它的储存方式比文件储存简单易用。
6.3.1 将数据存储到SharedPreferences中
三种获取SharedPreferences对象的方法:
1.Context类中的getSharedPreferences(), 此方法接受两个参数,
第一个参数是文件名,如果文件不存在则会创建一个。
默认的储存路径是:data/data/<package name>/shared_prefs/下
第二个参数是指定操作模式:MODE_PRIVATE和MODE_MULTI_PROCESS
MODE_PRIVATE表示只有当前应用程序可以对sharedPreferences文件读写。
MODE_MULTI_PROCESS 用于会有多个进程中对同一个sharedPreferences文件读取。
如果需要使用多个通过名字识别的存储文件,使用该方法。该方法需要指定文件名。
2.Activity类中的getPreferences(),
如果在activity中只需要一个存储文件的话,使用该方法。
由于该方法只能创建一个文件,因此不需要提供文件名,自动将当前活动的类名作为文件名
3.PreferenceManager类的getDefaultSharedPreferences()方法
静态方法,接收一份Context参数,自动使用当前应用程序的包名作为前缀来命名文件
向SharedPreferences文件中存储数据:
- 调用
edit()
获得SharedPreferences.Editor
对象; - 通过
putXXX()
方法添加数据; - 完成添加数据时调用
apply()
;
Button saveData = (Button) findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("name", "Tom");
editor.putInt("age", 28);
editor.putBoolean("married", false);
editor.apply();
}
});
6.3.2 从SharedPreferences中读取数据
SharedPreferences对象提供了一系列的get方法,这些get方法接收两个参数,第一个参数是键,第二个参数是默认值。
Button restoreData = (Button) findViewById(R.id.restore_data);
restoreData.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married", false);
Toast.makeText( MainActivity.this,name + age + married, Toast.LENGTH_SHORT).show();
Log.d("MainActivity", "name is" + name);
Log.d("MainActivity", "age is" + age);
Log.d("MainActivity", "married is" + married);
}
});
6.3.3 实现记住密码的功能
Button restoreData = (Button) findViewById(R.id.restore_data);
restoreData.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married", false);
Toast.makeText( MainActivity.this,name + age + married, Toast.LENGTH_SHORT).show();
Log.d("MainActivity", "name is" + name);
Log.d("MainActivity", "age is" + age);
Log.d("MainActivity", "married is" + married);
}
});
activity_login.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_login2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation = "vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.filepersistencetest.Login">
<EditText
android:id="@+id/account"
android:layout_height="wrap_content"
android:layout_width="match_parent"
></EditText>
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_width="match_parent"
></EditText>
<CheckBox
android:id="@+id/remember_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></CheckBox>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize = "18sp"
android:text = "Remember password"
></TextView>
<Button
android:id="@+id/login"
android:layout_height="60dp"
android:layout_width="match_parent"
android:text="Login"
></Button>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_login2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation = "vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.filepersistencetest.Login">
<EditText
android:id="@+id/account"
android:layout_height="wrap_content"
android:layout_width="match_parent"
></EditText>
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_width="match_parent"
></EditText>
<CheckBox
android:id="@+id/remember_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></CheckBox>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize = "18sp"
android:text = "Remember password"
></TextView>
<Button
android:id="@+id/login"
android:layout_height="60dp"
android:layout_width="match_parent"
android:text="Login"
></Button>
</LinearLayout>
界面效果:
Login.java的代码:
package com.example.filepersistencetest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
pref = PreferenceManager.getDefaultSharedPreferences(this);
accountEdit = (EditText) findViewById(R.id.account);
passwordEdit = (EditText) findViewById(R.id.password);
rememberPass = (CheckBox) findViewById(R.id.remember_pass);
login = (Button) findViewById(R.id.login);
boolean isRemember = pref.getBoolean("remember_password", false);
if(isRemember) {
String account = pref.getString("account", "");
String password = pref.getString("password", "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if(account.equals("123") && password.equals("123")) {
editor = pref.edit();
if(rememberPass.isChecked()) {
editor.putBoolean("remember_password", true);
editor.putString("account", account);
editor.putString("password", password);
} else {
editor.clear();
}
editor.apply();
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
}else {
Toast.makeText(Login.this,"account or passwrod is invalid", Toast.LENGTH_SHORT).show();
}
}
});
}
}
6.4 SQLite数据库存储
package com.example.filepersistencetest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
pref = PreferenceManager.getDefaultSharedPreferences(this);
accountEdit = (EditText) findViewById(R.id.account);
passwordEdit = (EditText) findViewById(R.id.password);
rememberPass = (CheckBox) findViewById(R.id.remember_pass);
login = (Button) findViewById(R.id.login);
boolean isRemember = pref.getBoolean("remember_password", false);
if(isRemember) {
String account = pref.getString("account", "");
String password = pref.getString("password", "");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if(account.equals("123") && password.equals("123")) {
editor = pref.edit();
if(rememberPass.isChecked()) {
editor.putBoolean("remember_password", true);
editor.putString("account", account);
editor.putString("password", password);
} else {
editor.clear();
}
editor.apply();
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
}else {
Toast.makeText(Login.this,"account or passwrod is invalid", Toast.LENGTH_SHORT).show();
}
}
});
}
}