Android学习(7)

数据存储——持久化技术

持久化技术

数据持久化就是指将在内存中的瞬时数据保存到存储设备中,保证即使在手机或电脑关机的情况下,这些数据仍然不会丢失。

保存在内存中的数据是处于瞬时状态,而保存在存储设备中的数据是处于持久状态,持久化技术提供一种机制可以使数据在瞬时状态和持久状态中进行转换。

Android中的数据持久化技术

Android系统中主要提供了三种方式用于简单地实现数据持久化功能,即文件存储、SharedPreferences存储以及数据库存储。

此外,还可以将数据保存在手机的SD卡中,但这种方式相对复杂且不那么安全。

文件存储

文件存储的特点是:不对存储的内容进行任何格式化处理,所有数据原封不动地保存到文件当中,因而较适合用于存储一些简单的文本数据或二进制数据。

将数据存储到文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void save() {
String data = "Data to save";
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

从文件中读取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}

SharedPreferences

SharedPreferences采用键值对的方式存储数据,当保存一条数据时,需要给这个数据提供一个对应的键,在读取数据的时候,可以通过这个键把对应的值取出来。

SharedPreferences支持多种不同数据的类型存储,如果存储的数据是整型,读取出来的数据也是整型。

将数据存储到SharedPreferences中

  1. Context类中的getSharedPreferences()方法
  2. Activity类中的getPreferences()方法
  3. PreferenceManager类中的getDefaultSharedPreferences()方法
1
2
3
4
5
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name","bob");
editor.putInt("age",28);
editor.putBoolean("married",false);
editor.apply();

SQLite数据库存储

Android系统内置了SQLite数据库,数据库可以用于存储大量复杂的关系数据,例如短信等。

创建数据库

Android系统的SQLiteOpenHelper帮助类,可以对数据库进行创建和升级。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
	public class MyDatabaseHhelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "Create table Book ("
+ "id integer primary key autoincrement,"
+ "author text,"
+ "price real,"
+ "pages integer,"
+ "name text)";

public static final String CREATE_CATEGORY = "Create table Category ("
+ "id integer primary key autoincrement,"
+ "category_name text,"
+ "category_code integer)";
private Context mContext;
public MyDatabaseHhelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
super(context,name,factory,version);
mContext=context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext,"category",Toast.LENGTH_SHORT).show();

}
}

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
private MyDatabaseHhelper myDatabaseHhelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDatabaseHhelper = new MyDatabaseHhelper(this,"BookStore.db",null,2);
Button button=(Button)findViewById(R.id.create_database);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myDatabaseHhelper.getWritableDatabase();
}
});

添加数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Button addData = (Button) findViewById(R.id.add_data);
addData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = myDatabaseHhelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);db.insert("Book", null, values); // 插入第一条数据
values.clear();
// 开始组装第二条数据
values.put("name", "The Lost Symbol");
values.put("author", "Dan Brown");
values.put("pages", 510);
values.put("price", 19.95);
db.insert("Book", null, values); // 插入第二条数据
}
});

查询数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Button query = (Button)findViewById(R.id.query_data);
query.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = myDatabaseHhelper.getWritableDatabase();
Cursor cursor = db.query("Book",null,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndex("name"));
String author = cursor.getString(cursor.getColumnIndex("author"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
double price = cursor.getDouble(cursor.getColumnIndex("price"));
Log.d("name","name is "+name);
Log.d("author","author is "+author);
Log.d("pages","pages is "+pages);
Log.d("price","price is "+price);
}while(cursor.moveToNext());
}
cursor.close();

}
});

更新数据

1
2
3
4
5
6
7
8
9
10
Button update = (Button)findViewById(R.id.update_data);
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = myDatabaseHhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price","10.2");
db.update("Book",values,"name =?",new String[]{"The Da Vinci Code"});
}
});