6.1持久化技術(shù)簡介
持久化是將內(nèi)存中的數(shù)據(jù)存儲在存儲設(shè)備的過程.Android提供文件存儲,SharedPreference存儲和數(shù)據(jù)庫存儲.
6.2文件存儲
不對存儲的內(nèi)容做任何處理,適合存儲文本數(shù)據(jù)或二進(jìn)制數(shù)據(jù);對于復(fù)雜的文本數(shù)據(jù)需要定義格式g
6.2.1將數(shù)據(jù)存儲到文件中
步驟:
1.context提供openFileOutput(fileName,model),獲得FileOutputStream對象.
2.使用Java流的方式將數(shù)據(jù)寫入文件.
注意:
- fileName不包含路徑,默認(rèn)存儲在/data/data/<packagename>/files/目錄中.
- model可選參數(shù)是MODE_PRIVATE 和 MODE_APPEND.MODE_PRIVATE 是默認(rèn)模式,表示當(dāng)指定同樣文件名的時候,所寫入的內(nèi)容將會覆蓋原文件中的內(nèi)容; MODE_APPEND表示如果該文件已存在就往文件里面追加內(nèi)容,不存在就創(chuàng)建新文件.
示例:
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
6.2.2從文件中讀取數(shù)據(jù)
步驟:
1.context提供openFileInput(fileName),獲得FileInputStream對象.
2.使用Java流的方式將數(shù)據(jù)讀出.
注意:
- fileName不需要路徑,默認(rèn)從/data/data/<package name>/files/中讀取.
示例:
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
6.3SharedPreferences存儲
使用鍵值對存儲,支持多類型的存儲.
6.3.1將數(shù)據(jù)存儲到SharedPreferences中
步驟:
1.獲取SharedPreferences對象.包括三種方法.
- context類的getSharedPreferences(fileName,model).若文件不存在則新建一個.fileName不需要路徑,默認(rèn)存儲在/data/data/<packagename>/shared_prefs/目錄下.model包括MODE_PRIVATE 和 MODE_MULTI_PROCESS.MODE_PRIVATE 指定只有當(dāng)前應(yīng)用可以對本文件進(jìn)行讀寫;MODE_MULTI_PROCESS指定可以多個進(jìn)程對該文件進(jìn)行讀寫
- Activity類的getPreferences(model).該方法會自動將當(dāng)前活動的類名作為SharedPreferences的文件名.
- PreferenceManager類的getDefaultSharedPreferences().接受
2.向SharedPreferences中存儲數(shù)據(jù).
?1.調(diào)用SharedPreferences的edit()獲取SharedPreferences.Editor對象.
?2.向 SharedPreferences.Editor 對象中添加數(shù)據(jù).put<type>().putStream()/putInt()...
?3.調(diào)用commit()提交.
注意: - 生成的是xml文件.
示例:
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name", "Tom");
editor.putInt("age", 28);editor.putBoolean("married", false);
editor.commit();
6.3.2從 SharedPreferences 中讀取數(shù)據(jù)
1.使用getSharedPreferences(fileName,Model)獲取SharedPreferences對象.
2.使用get<type>(keyName,defaultValue).keyName是存儲是使用的鍵,defaultValue是當(dāng)找不到對應(yīng)的鍵時返回的值.
示例:
SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married", false);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "age is " + age);
Log.d("MainActivity", "married is " + married);
6.3.3實現(xiàn)記住密碼功能
6.4SQLite數(shù)據(jù)庫存儲
安卓內(nèi)置了SQLite數(shù)據(jù)庫,當(dāng)儲存較為復(fù)雜的數(shù)據(jù)時,優(yōu)先考慮數(shù)據(jù)庫存數(shù).使用SQLiteOpenHelper(抽象類)來操作數(shù)據(jù)庫.db.exeSQL(commandStream).commandStreamString類型的命令語句.
6.4.1創(chuàng)建數(shù)據(jù)庫
步驟:
1.使用getReadableDatabase()或getWritableDatabase()創(chuàng)建或打開一個已存在的數(shù)據(jù)庫(若不存在則創(chuàng)建).
2.使用構(gòu)造方法,傳入context,數(shù)據(jù)庫名,自定義的Cursor(通常為null),版本號.構(gòu)造出SQLiteOpenHelper實例后調(diào)用getWritableDatabase()或getReadableDatabase()即可創(chuàng)建.默認(rèn)目錄在/data/data/<package name>/databases/下.
注意:
- 當(dāng)數(shù)據(jù)庫不可寫入時(如磁盤已滿)getReadableDatabase()將以只讀方式打開數(shù)據(jù)庫,getWritableDatabase()將返回異常.
- 創(chuàng)建數(shù)據(jù)庫時,onCreate()也會被執(zhí)行,可以將邏輯寫入.
示例:
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "create table book ("+ "id integer primary key autoincrement, "+ "author text, "+ "price real, "+ "pages integer, "+ "name text)";
private Context mContext;
public MyDatabaseHelper(Context context, String name, CursorFactoryfactory, 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) {
}
}
6.4.2升級數(shù)據(jù)庫
onUpgrade()用于升級數(shù)據(jù)庫.當(dāng)構(gòu)造函數(shù)傳入的參數(shù)大于初始值值,就會執(zhí)行.
6.4.3添加數(shù)據(jù)
instead(tableName,null,ContentValues).ContentValues通過put()向ContentValues傳入數(shù)據(jù).
示例:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();// 開始組裝第一條數(shù)據(jù)
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); // 插入第一條數(shù)據(jù)
values.clear();// 開始組裝第二條數(shù)據(jù)
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); // 插入第二條數(shù)據(jù)
6.4.4更新數(shù)據(jù)
update(tableName,ContentValue,約束1,約束2)第三第四參數(shù)用于約束更新某一行或某幾行,不指定默認(rèn)更新所有行.
示例:
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name = ?", new String[] { "The DaVinci Code" });//String數(shù)組為"name = ?"的"?"提供值.
6.4.5刪除數(shù)據(jù):
delete(tableName,約束1,約束2).第二茵瘾、第三個參數(shù)又是用于去約束刪除某一行或某幾行的數(shù)據(jù),不指定的話默認(rèn)就是刪除所有行.
示例:
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Book", "pages > ?", new String[] { "500" });
查詢數(shù)據(jù)
query().
query()方法參數(shù) | 對應(yīng) SQL 部分 | 描述 |
---|---|---|
table | from table_name | 指定查詢的表名 |
columns | select column1, column2 | 指定查詢的列名 |
selection | where column = value | 指定 where 的約束條件 |
selectionArgs | 為 where 中的占位符提供具體的值 | |
groupBy | group by column | 指定需要 group by 的列 |
having | having column = value | 對 group by 后的結(jié)果進(jìn)一步約束 |
orderBy | order by column1, column2 | 指定查詢結(jié)果的排序方式 |
示例:
SQLiteDatabase db = dbHelper.getWritableDatabase();// 查詢Book表中所有的數(shù)據(jù)
Cursor cursor = db.query("Book", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {// 遍歷Cursor對象,取出數(shù)據(jù)并打印
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("MainActivity", "book name is " + name);
Log.d("MainActivity", "book author is " + author);
Log.d("MainActivity", "book pages is " + pages);
Log.d("MainActivity", "book price is " + price);
} while (cursor.moveToNext());}cursor.close();
}
6.4.7使用SQL操作數(shù)據(jù)庫
添加數(shù)據(jù)的方法如下:
db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",new String[] { "The Da Vinci Code", "Dan Brown", "454", "16.96" });
更新數(shù)據(jù)的方法如下:
db.execSQL("update Book set price = ? where name = ?", new String[] { "10.99","The Da Vinci Code" });
刪除數(shù)據(jù)的方法如下:
db.execSQL("delete from Book where pages > ?", new String[] { "500" });
查詢數(shù)據(jù)的方法如下:
db.rawQuery("select * from Book", null);
總結(jié)
1.Android提供文件存儲,SharedPreference存儲和數(shù)據(jù)庫存儲.
2.文件存儲適合二進(jìn)制數(shù)據(jù)或者字符串?dāng)?shù)據(jù);SharedPreferences存儲鍵值對;數(shù)據(jù)庫存儲適合較復(fù)雜的數(shù)據(jù).
3.文件存儲提供openFileOutput和openFileInput.
4.SharedPreferences存儲通過SharedPreferences.
5.數(shù)據(jù)庫通過SQLiteOpenHelper創(chuàng)建和升級數(shù)據(jù)庫,SQLiteDatabase的execSQL()開增刪改,rawQuery()查詢數(shù)據(jù)庫.