Android編程中的5種數(shù)據(jù)存儲(chǔ)方式
本文介紹Android平臺(tái)進(jìn)行數(shù)據(jù)存儲(chǔ)的五大方式,分別如下:
1 使用SharedPreferences存儲(chǔ)數(shù)據(jù)
2 文件存儲(chǔ)數(shù)據(jù)
3 SQLite數(shù)據(jù)庫(kù)存儲(chǔ)數(shù)據(jù)
4 使用ContentProvider存儲(chǔ)數(shù)據(jù)
5 網(wǎng)絡(luò)存儲(chǔ)數(shù)據(jù)
下面詳細(xì)講解這五種方式的特點(diǎn)
第一種: 使用SharedPreferences存儲(chǔ)數(shù)據(jù)
適用范圍:保存少量的數(shù)據(jù),且這些數(shù)據(jù)的格式非常簡(jiǎn)單:字符串型、基本類型的值。比如應(yīng)用程序的各種配置信息(如是否打開音效、是否使用震動(dòng)效果、小游戲的玩家積分等),解鎖口 令密碼等
核心原理:保存基于XML文件存儲(chǔ)的key-value鍵值對(duì)數(shù)據(jù),通常用來存儲(chǔ)一些簡(jiǎn)單的配置信息。通過DDMS的File Explorer面板,展開文件瀏覽樹,很明顯SharedPreferences數(shù)據(jù)總是存儲(chǔ)在/data/data/<package name>/shared_prefs目錄下。SharedPreferences對(duì)象本身只能獲取數(shù)據(jù)而不支持存儲(chǔ)和修改,存儲(chǔ)修改是通過SharedPreferences.edit()獲取的內(nèi)部接口Editor對(duì)象實(shí)現(xiàn)。 SharedPreferences本身是一 個(gè)接口,程序無法直接創(chuàng)建SharedPreferences實(shí)例,只能通過Context提供的getSharedPreferences(String name, int mode)方法來獲取SharedPreferences實(shí)例,該方法中name表示要操作的xml文件名,第二個(gè)參數(shù)具體如下:
Context.MODE_PRIVATE: 指定該SharedPreferences數(shù)據(jù)只能被本應(yīng)用程序讀、寫。
Context.MODE_WORLD_READABLE: 指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序讀,但不能寫。
Context.MODE_WORLD_WRITEABLE: 指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序讀,寫
Editor有如下主要重要方法:
SharedPreferences.Editor clear():清空SharedPreferences里所有數(shù)據(jù)
SharedPreferences.Editor putXxx(String key , xxx value): 向SharedPreferences存入指定key對(duì)應(yīng)的數(shù)據(jù),其中xxx 可以是boolean,float,int等各種基本類型據(jù)
SharedPreferences.Editor remove(): 刪除SharedPreferences中指定key對(duì)應(yīng)的數(shù)據(jù)項(xiàng)
boolean commit(): 當(dāng)Editor編輯完成后,使用該方法提交修改
實(shí)際案例:運(yùn)行界面如下

這里只提供了兩個(gè)按鈕和一個(gè)輸入文本框,布局簡(jiǎn)單,故在此不給出界面布局文件了,程序核心代碼如下:
class ViewOcl implements View.OnClickListener{
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnSet:
//步驟1:獲取輸入值
String code = txtCode.getText().toString().trim();
//步驟2-1:創(chuàng)建一個(gè)SharedPreferences.Editor接口對(duì)象,lock表示要寫入的XML文件名,MODE_WORLD_WRITEABLE寫操作
SharedPreferences.Editor editor = getSharedPreferences("lock", MODE_WORLD_WRITEABLE).edit();
//步驟2-2:將獲取過來的值放入文件
editor.putString("code", code);
//步驟3:提交
editor.commit();
Toast.makeText(getApplicationContext(), "口令設(shè)置成功", Toast.LENGTH_LONG).show();
break;
case R.id.btnGet:
//步驟1:創(chuàng)建一個(gè)SharedPreferences接口對(duì)象
SharedPreferences read = getSharedPreferences("lock", MODE_WORLD_READABLE);
//步驟2:獲取文件中的值
String value = read.getString("code", "");
Toast.makeText(getApplicationContext(), "口令為:"+value, Toast.LENGTH_LONG).show();
break;
}
}
}
讀寫其他應(yīng)用的SharedPreferences: 步驟如下
1、在創(chuàng)建SharedPreferences時(shí),指定MODE_WORLD_READABLE模式,表明該SharedPreferences數(shù)據(jù)可以被其他程序讀取
2、創(chuàng)建其他應(yīng)用程序?qū)?yīng)的Context:
Context pvCount = createPackageContext("com.tony.app", Context.CONTEXT_IGNORE_SECURITY);這里的com.tony.app就是其他程序的包名
3、使用其他程序的Context獲取對(duì)應(yīng)的SharedPreferences
SharedPreferences read = pvCount.getSharedPreferences("lock", Context.MODE_WORLD_READABLE);
4、如果是寫入數(shù)據(jù),使用Editor接口即可,所有其他操作均和前面一致。
SharedPreferences對(duì)象與SQLite數(shù)據(jù)庫(kù)相比,免去了創(chuàng)建數(shù)據(jù)庫(kù),創(chuàng)建表,寫SQL語(yǔ)句等諸多操作,相對(duì)而言更加方便,簡(jiǎn)潔。但是SharedPreferences也有其自身缺陷,比如其職能存儲(chǔ)boolean,int,float,long和String五種簡(jiǎn)單的數(shù)據(jù)類型,比如其無法進(jìn)行條件查詢等。所以不論SharedPreferences的數(shù)據(jù)存儲(chǔ)操作是如何簡(jiǎn)單,它也只能是存儲(chǔ)方式的一種補(bǔ)充,而無法完全替代如SQLite數(shù)據(jù)庫(kù)這樣的其他數(shù)據(jù)存儲(chǔ)方式。
第二種: 文件存儲(chǔ)數(shù)據(jù)
核心原理: Context提供了兩個(gè)方法來打開數(shù)據(jù)文件里的文件IO流 FileInputStream openFileInput(String name); FileOutputStream(String name , int mode),這兩個(gè)方法第一個(gè)參數(shù) 用于指定文件名,第二個(gè)參數(shù)指定打開文件的模式。具體有以下值可選:
MODE_PRIVATE:為默認(rèn)操作模式,代表該文件是私有數(shù)據(jù),只能被應(yīng)用本身訪問,在該模式下,寫入的內(nèi)容會(huì)覆蓋原文件的內(nèi)容,如果想把新寫入的內(nèi)容追加到原文件中???nbsp; 以使用Context.MODE_APPEND
MODE_APPEND:模式會(huì)檢查文件是否存在,存在就往文件追加內(nèi)容,否則就創(chuàng)建新文件。
MODE_WORLD_READABLE:表示當(dāng)前文件可以被其他應(yīng)用讀?。?br />
MODE_WORLD_WRITEABLE:表示當(dāng)前文件可以被其他應(yīng)用寫入。
除此之外,Context還提供了如下幾個(gè)重要的方法:
getDir(String name , int mode):在應(yīng)用程序的數(shù)據(jù)文件夾下獲取或者創(chuàng)建name對(duì)應(yīng)的子目錄
File getFilesDir():獲取該應(yīng)用程序的數(shù)據(jù)文件夾得絕對(duì)路徑
String[] fileList():返回該應(yīng)用數(shù)據(jù)文件夾的全部文件
實(shí)際案例:界面沿用上圖
核心代碼如下:
public String read() {
try {
FileInputStream inStream = this.openFileInput("message.txt");
byte[] buffer = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder();
while ((hasRead = inStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, hasRead));
}
inStream.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String msg){
// 步驟1:獲取輸入值
if(msg == null) return;
try {
// 步驟2:創(chuàng)建一個(gè)FileOutputStream對(duì)象,MODE_APPEND追加模式
FileOutputStream fos = openFileOutput("message.txt",
MODE_APPEND);
// 步驟3:將獲取過來的值放入文件
fos.write(msg.getBytes());
// 步驟4:關(guān)閉數(shù)據(jù)流
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
openFileOutput()方法的第一參數(shù)用于指定文件名稱,不能包含路徑分隔符“/” ,如果文件不存在,Android 會(huì)自動(dòng)創(chuàng)建它。創(chuàng)建的文件保存在/data/data/<package name>/files目錄,如: /data/data/cn.tony.app/files/message.txt,
下面講解某些特殊文件讀寫需要注意的地方:
讀寫sdcard上的文件
其中讀寫步驟按如下進(jìn)行:
1、調(diào)用Environment的getExternalStorageState()方法判斷手機(jī)上是否插了sd卡,且應(yīng)用程序具有讀寫SD卡的權(quán)限,如下代碼將返回true
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
2、調(diào)用Environment.getExternalStorageDirectory()方法來獲取外部存儲(chǔ)器,也就是SD卡的目錄,或者使用"/mnt/sdcard/"目錄
3、使用IO流操作SD卡上的文件
注意點(diǎn):手機(jī)應(yīng)該已插入SD卡,對(duì)于模擬器而言,可通過mksdcard命令來創(chuàng)建虛擬存儲(chǔ)卡
必須在AndroidManifest.xml上配置讀寫SD卡的權(quán)限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
案例代碼:
// 文件寫操作函數(shù)
private void write(String content) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) { // 如果sdcard存在
File file = new File(Environment.getExternalStorageDirectory()
.toString()
+ File.separator
+ DIR
+ File.separator
+ FILENAME); // 定義File類對(duì)象
if (!file.getParentFile().exists()) { // 父文件夾不存在
file.getParentFile().mkdirs(); // 創(chuàng)建文件夾
}
PrintStream out = null; // 打印流對(duì)象用于輸出
try {
out = new PrintStream(new FileOutputStream(file, true)); // 追加文件
out.println(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close(); // 關(guān)閉打印流
}
}
} else { // SDCard不存在,使用Toast提示用戶
Toast.makeText(this, "保存失敗,SD卡不存在!", Toast.LENGTH_LONG).show();
}
}
// 文件讀操作函數(shù)
private String read() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) { // 如果sdcard存在
File file = new File(Environment.getExternalStorageDirectory()
.toString()
+ File.separator
+ DIR
+ File.separator
+ FILENAME); // 定義File類對(duì)象
if (!file.getParentFile().exists()) { // 父文件夾不存在
file.getParentFile().mkdirs(); // 創(chuàng)建文件夾
}
Scanner scan = null; // 掃描輸入
StringBuilder sb = new StringBuilder();
try {
scan = new Scanner(new FileInputStream(file)); // 實(shí)例化Scanner
while (scan.hasNext()) { // 循環(huán)讀取
sb.append(scan.next() + "\n"); // 設(shè)置文本
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scan != null) {
scan.close(); // 關(guān)閉打印流
}
}
} else { // SDCard不存在,使用Toast提示用戶
Toast.makeText(this, "讀取失敗,SD卡不存在!", Toast.LENGTH_LONG).show();
}
return null;
}
第三種:SQLite存儲(chǔ)數(shù)據(jù)
SQLite是輕量級(jí)嵌入式數(shù)據(jù)庫(kù)引擎,它支持 SQL 語(yǔ)言,并且只利用很少的內(nèi)存就有很好的性能?,F(xiàn)在的主流移動(dòng)設(shè)備像Android、iPhone等都使用SQLite作為復(fù)雜數(shù)據(jù)的存儲(chǔ)引擎,在我們?yōu)橐苿?dòng)設(shè)備開發(fā)應(yīng)用程序時(shí),也許就要使用到SQLite來存儲(chǔ)我們大量的數(shù)據(jù),所以我們就需要掌握移動(dòng)設(shè)備上的SQLite開發(fā)技巧
SQLiteDatabase類為我們提供了很多種方法,上面的代碼中基本上囊括了大部分的數(shù)據(jù)庫(kù)操作;對(duì)于添加、更新和刪除來說,我們都可以使用
db.executeSQL(String sql); db.executeSQL(String sql, Object[] bindArgs); //sql語(yǔ)句中使用占位符,然后第二個(gè)參數(shù)是實(shí)際的參數(shù)集
除了統(tǒng)一的形式之外,他們還有各自的操作方法:
db.insert(String table, String nullColumnHack, ContentValues values); db.update(String table, Contentvalues values, String whereClause, String whereArgs); db.delete(String table, String whereClause, String whereArgs);
以上三個(gè)方法的第一個(gè)參數(shù)都是表示要操作的表名;insert中的第二個(gè)參數(shù)表示如果插入的數(shù)據(jù)每一列都為空的話,需要指定此行中某一列的名稱,系統(tǒng)將此列設(shè)置為NULL,不至于出現(xiàn)錯(cuò)誤;insert中的第三個(gè)參數(shù)是ContentValues類型的變量,是鍵值對(duì)組成的Map,key代表列名,value代表該列要插入的值;update的第二個(gè)參數(shù)也很類似,只不過它是更新該字段key為最新的value值,第三個(gè)參數(shù)whereClause表示W(wǎng)HERE表達(dá)式,比如“age > ? and age < ?”等,最后的whereArgs參數(shù)是占位符的實(shí)際參數(shù)值;delete方法的參數(shù)也是一樣
下面給出demo
數(shù)據(jù)的添加
1.使用insert方法
ContentValues cv = new ContentValues();//實(shí)例化一個(gè)ContentValues用來裝載待插入的數(shù)據(jù)
cv.put("title","you are beautiful");//添加title
cv.put("weather","sun"); //添加weather
cv.put("context","xxxx"); //添加context
String publish = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date());
cv.put("publish ",publish); //添加publish
db.insert("diary",null,cv);//執(zhí)行插入操作
2.使用execSQL方式來實(shí)現(xiàn)
String sql = "insert into user(username,password) values ('Jack Johnson','iLovePopMuisc');//插入操作的SQL語(yǔ)句
db.execSQL(sql);//執(zhí)行SQL語(yǔ)句
數(shù)據(jù)的刪除
同樣有2種方式可以實(shí)現(xiàn)
String whereClause = "username=?";//刪除的條件
String[] whereArgs = {"Jack Johnson"};//刪除的條件參數(shù)
db.delete("user",whereClause,whereArgs);//執(zhí)行刪除
使用execSQL方式的實(shí)現(xiàn)
String sql = "delete from user where username='Jack Johnson'";//刪除操作的SQL語(yǔ)句 db.execSQL(sql);//執(zhí)行刪除操作
數(shù)據(jù)修改
同上,仍是2種方式
ContentValues cv = new ContentValues();//實(shí)例化ContentValues
cv.put("password","iHatePopMusic");//添加要更改的字段及內(nèi)容
String whereClause = "username=?";//修改條件
String[] whereArgs = {"Jack Johnson"};//修改條件的參數(shù)
db.update("user",cv,whereClause,whereArgs);//執(zhí)行修改
使用execSQL方式的實(shí)現(xiàn)
String sql = "update user set password = 'iHatePopMusic' where username='Jack Johnson'";//修改的SQL語(yǔ)句 db.execSQL(sql);//執(zhí)行修改
數(shù)據(jù)查詢
下面來說說查詢操作。查詢操作相對(duì)于上面的幾種操作要復(fù)雜些,因?yàn)槲覀兘?jīng)常要面對(duì)著各種各樣的查詢條件,所以系統(tǒng)也考慮到這種復(fù)雜性,為我們提供了較為豐富的查詢形式:
db.rawQuery(String sql, String[] selectionArgs); db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy); db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit); db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
上面幾種都是常用的查詢方法,第一種最為簡(jiǎn)單,將所有的SQL語(yǔ)句都組織到一個(gè)字符串中,使用占位符代替實(shí)際參數(shù),selectionArgs就是占位符實(shí)際參數(shù)集;
各參數(shù)說明:
table:表名稱
colums:表示要查詢的列所有名稱集
selection:表示W(wǎng)HERE之后的條件語(yǔ)句,可以使用占位符
selectionArgs:條件語(yǔ)句的參數(shù)數(shù)組
groupBy:指定分組的列名
having:指定分組條件,配合groupBy使用
orderBy:y指定排序的列名
limit:指定分頁(yè)參數(shù)
distinct:指定“true”或“false”表示要不要過濾重復(fù)值
Cursor:返回值,相當(dāng)于結(jié)果集ResultSet
最后,他們同時(shí)返回一個(gè)Cursor對(duì)象,代表數(shù)據(jù)集的游標(biāo),有點(diǎn)類似于JavaSE中的ResultSet。下面是Cursor對(duì)象的常用方法:
c.move(int offset); //以當(dāng)前位置為參考,移動(dòng)到指定行 c.moveToFirst(); //移動(dòng)到第一行 c.moveToLast(); //移動(dòng)到最后一行 c.moveToPosition(int position); //移動(dòng)到指定行 c.moveToPrevious(); //移動(dòng)到前一行 c.moveToNext(); //移動(dòng)到下一行 c.isFirst(); //是否指向第一條 c.isLast(); //是否指向最后一條 c.isBeforeFirst(); //是否指向第一條之前 c.isAfterLast(); //是否指向最后一條之后 c.isNull(int columnIndex); //指定列是否為空(列基數(shù)為0) c.isClosed(); //游標(biāo)是否已關(guān)閉 c.getCount(); //總數(shù)據(jù)項(xiàng)數(shù) c.getPosition(); //返回當(dāng)前游標(biāo)所指向的行數(shù) c.getColumnIndex(String columnName);//返回某列名對(duì)應(yīng)的列索引值 c.getString(int columnIndex); //返回當(dāng)前行指定列的值
實(shí)現(xiàn)代碼
String[] params = {12345,123456};
Cursor cursor = db.query("user",columns,"ID=?",params,null,null,null);//查詢并獲得游標(biāo)
if(cursor.moveToFirst()){//判斷游標(biāo)是否為空
for(int i=0;i<cursor.getCount();i++){
cursor.move(i);//移動(dòng)到指定記錄
String username = cursor.getString(cursor.getColumnIndex("username");
String password = cursor.getString(cursor.getColumnIndex("password"));
}
}
通過rawQuery實(shí)現(xiàn)的帶參數(shù)查詢
Cursor result=db.rawQuery("SELECT ID, name, inventory FROM mytable");
//Cursor c = db.rawQuery("s name, inventory FROM mytable where ID=?",new Stirng[]{"123456"});
result.moveToFirst();
while (!result.isAfterLast()) {
int id=result.getInt(0);
String name=result.getString(1);
int inventory=result.getInt(2);
// do something useful with these
result.moveToNext();
}
result.close();
在上面的代碼示例中,已經(jīng)用到了這幾個(gè)常用方法中的一些,關(guān)于更多的信息,大家可以參考官方文檔中的說明。
最后當(dāng)我們完成了對(duì)數(shù)據(jù)庫(kù)的操作后,記得調(diào)用SQLiteDatabase的close()方法釋放數(shù)據(jù)庫(kù)連接,否則容易出現(xiàn)SQLiteException。
上面就是SQLite的基本應(yīng)用,但在實(shí)際開發(fā)中,為了能夠更好的管理和維護(hù)數(shù)據(jù)庫(kù),我們會(huì)封裝一個(gè)繼承自SQLiteOpenHelper類的數(shù)據(jù)庫(kù)操作類,然后以這個(gè)類為基礎(chǔ),再封裝我們的業(yè)務(wù)邏輯方法。
這里直接使用案例講解:下面是案例demo的界面

SQLiteOpenHelper類介紹
SQLiteOpenHelper是SQLiteDatabase的一個(gè)幫助類,用來管理數(shù)據(jù)庫(kù)的創(chuàng)建和版本的更新。一般是建立一個(gè)類繼承它,并實(shí)現(xiàn)它的onCreate和onUpgrade方法。
| 方法名 | 方法描述 |
|---|---|
| SQLiteOpenHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version) |
構(gòu)造方法,其中 context 程序上下文環(huán)境 即:XXXActivity.this; name :數(shù)據(jù)庫(kù)名字; factory:游標(biāo)工廠,默認(rèn)為null,即為使用默認(rèn)工廠; version 數(shù)據(jù)庫(kù)版本號(hào) |
| onCreate(SQLiteDatabase db) | 創(chuàng)建數(shù)據(jù)庫(kù)時(shí)調(diào)用 |
| onUpgrade(SQLiteDatabase db,int oldVersion , int newVersion) | 版本更新時(shí)調(diào)用 |
| getReadableDatabase() | 創(chuàng)建或打開一個(gè)只讀數(shù)據(jù)庫(kù) |
| getWritableDatabase() | 創(chuàng)建或打開一個(gè)讀寫數(shù)據(jù)庫(kù) |
首先創(chuàng)建數(shù)據(jù)庫(kù)類
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class SqliteDBHelper extends SQLiteOpenHelper {
// 步驟1:設(shè)置常數(shù)參量
private static final String DATABASE_NAME = "diary_db";
private static final int VERSION = 1;
private static final String TABLE_NAME = "diary";
// 步驟2:重載構(gòu)造方法
public SqliteDBHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
/*
* 參數(shù)介紹:context 程序上下文環(huán)境 即:XXXActivity.this
* name 數(shù)據(jù)庫(kù)名字
* factory 接收數(shù)據(jù),一般情況為null
* version 數(shù)據(jù)庫(kù)版本號(hào)
*/
public SqliteDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
//數(shù)據(jù)庫(kù)第一次被創(chuàng)建時(shí),onCreate()會(huì)被調(diào)用
@Override
public void onCreate(SQLiteDatabase db) {
// 步驟3:數(shù)據(jù)庫(kù)表的創(chuàng)建
String strSQL = "create table "
+ TABLE_NAME
+ "(tid integer primary key autoincrement,title varchar(20),weather varchar(10),context text,publish date)";
//步驟4:使用參數(shù)db,創(chuàng)建對(duì)象
db.execSQL(strSQL);
}
//數(shù)據(jù)庫(kù)版本變化時(shí),會(huì)調(diào)用onUpgrade()
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
}
正如上面所述,數(shù)據(jù)庫(kù)第一次創(chuàng)建時(shí)onCreate方法會(huì)被調(diào)用,我們可以執(zhí)行創(chuàng)建表的語(yǔ)句,當(dāng)系統(tǒng)發(fā)現(xiàn)版本變化之后,會(huì)調(diào)用onUpgrade方法,我們可以執(zhí)行修改表結(jié)構(gòu)等語(yǔ)句。
我們需要一個(gè)Dao,來封裝我們所有的業(yè)務(wù)方法,代碼如下:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.chinasoft.dbhelper.SqliteDBHelper;
public class DiaryDao {
private SqliteDBHelper sqliteDBHelper;
private SQLiteDatabase db;
// 重寫構(gòu)造方法
public DiaryDao(Context context) {
this.sqliteDBHelper = new SqliteDBHelper(context);
db = sqliteDBHelper.getWritableDatabase();
}
// 讀操作
public String execQuery(final String strSQL) {
try {
System.out.println("strSQL>" + strSQL);
// Cursor相當(dāng)于JDBC中的ResultSet
Cursor cursor = db.rawQuery(strSQL, null);
// 始終讓cursor指向數(shù)據(jù)庫(kù)表的第1行記錄
cursor.moveToFirst();
// 定義一個(gè)StringBuffer的對(duì)象,用于動(dòng)態(tài)拼接字符串
StringBuffer sb = new StringBuffer();
// 循環(huán)游標(biāo),如果不是最后一項(xiàng)記錄
while (!cursor.isAfterLast()) {
sb.append(cursor.getInt(0) + "/" + cursor.getString(1) + "/"
+ cursor.getString(2) + "/" + cursor.getString(3) + "/"
+ cursor.getString(4)+"#");
//cursor游標(biāo)移動(dòng)
cursor.moveToNext();
}
db.close();
return sb.deleteCharAt(sb.length()-1).toString();
} catch (RuntimeException e) {
e.printStackTrace();
return null;
}
}
// 寫操作
public boolean execOther(final String strSQL) {
db.beginTransaction(); //開始事務(wù)
try {
System.out.println("strSQL" + strSQL);
db.execSQL(strSQL);
db.setTransactionSuccessful(); //設(shè)置事務(wù)成功完成
db.close();
return true;
} catch (RuntimeException e) {
e.printStackTrace();
return false;
}finally {
db.endTransaction(); //結(jié)束事務(wù)
}
}
}
我們?cè)贒ao構(gòu)造方法中實(shí)例化sqliteDBHelper并獲取一個(gè)SQLiteDatabase對(duì)象,作為整個(gè)應(yīng)用的數(shù)據(jù)庫(kù)實(shí)例;在增刪改信息時(shí),我們采用了事務(wù)處理,確保數(shù)據(jù)完整性;最后要注意釋放數(shù)據(jù)庫(kù)資源db.close(),這一個(gè)步驟在我們整個(gè)應(yīng)用關(guān)閉時(shí)執(zhí)行,這個(gè)環(huán)節(jié)容易被忘記,所以朋友們要注意。
我們獲取數(shù)據(jù)庫(kù)實(shí)例時(shí)使用了getWritableDatabase()方法,也許朋友們會(huì)有疑問,在getWritableDatabase()和getReadableDatabase()中,你為什么選擇前者作為整個(gè)應(yīng)用的數(shù)據(jù)庫(kù)實(shí)例呢?在這里我想和大家著重分析一下這一點(diǎn)。
我們來看一下SQLiteOpenHelper中的getReadableDatabase()方法:
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
// 如果發(fā)現(xiàn)mDatabase不為空并且已經(jīng)打開則直接返回
return mDatabase;
}
if (mIsInitializing) {
// 如果正在初始化則拋出異常
throw new IllegalStateException("getReadableDatabase called recursively");
}
// 開始實(shí)例化數(shù)據(jù)庫(kù)mDatabase
try {
// 注意這里是調(diào)用了getWritableDatabase()方法
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null)
throw e; // Can't open a temp database read-only!
Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
// 如果無法以可讀寫模式打開數(shù)據(jù)庫(kù) 則以只讀方式打開
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mContext.getDatabasePath(mName).getPath();// 獲取數(shù)據(jù)庫(kù)路徑
// 以只讀方式打開數(shù)據(jù)庫(kù)
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to "
+ mNewVersion + ": " + path);
}
onOpen(db);
Log.w(TAG, "Opened " + mName + " in read-only mode");
mDatabase = db;// 為mDatabase指定新打開的數(shù)據(jù)庫(kù)
return mDatabase;// 返回打開的數(shù)據(jù)庫(kù)
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase)
db.close();
}
}
在getReadableDatabase()方法中,首先判斷是否已存在數(shù)據(jù)庫(kù)實(shí)例并且是打開狀態(tài),如果是,則直接返回該實(shí)例,否則試圖獲取一個(gè)可讀寫模式的數(shù)據(jù)庫(kù)實(shí)例,如果遇到磁盤空間已滿等情況獲取失敗的話,再以只讀模式打開數(shù)據(jù)庫(kù),獲取數(shù)據(jù)庫(kù)實(shí)例并返回,然后為mDatabase賦值為最新打開的數(shù)據(jù)庫(kù)實(shí)例。既然有可能調(diào)用到getWritableDatabase()方法,我們就要看一下了:
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
// 如果mDatabase不為空已打開并且不是只讀模式 則返回該實(shí)例
return mDatabase;
}
if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}
// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock. To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.
boolean success = false;
SQLiteDatabase db = null;
// 如果mDatabase不為空則加鎖 阻止其他的操作
if (mDatabase != null)
mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
// 打開或創(chuàng)建數(shù)據(jù)庫(kù)
db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}
// 獲取數(shù)據(jù)庫(kù)版本(如果剛創(chuàng)建的數(shù)據(jù)庫(kù),版本為0)
int version = db.getVersion();
// 比較版本(我們代碼中的版本mNewVersion為1)
if (version != mNewVersion) {
db.beginTransaction();// 開始事務(wù)
try {
if (version == 0) {
// 執(zhí)行我們的onCreate方法
onCreate(db);
} else {
// 如果我們應(yīng)用升級(jí)了mNewVersion為2,而原版本為1則執(zhí)行onUpgrade方法
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);// 設(shè)置最新版本
db.setTransactionSuccessful();// 設(shè)置事務(wù)成功
} finally {
db.endTransaction();// 結(jié)束事務(wù)
}
}
onOpen(db);
success = true;
return db;// 返回可讀寫模式的數(shù)據(jù)庫(kù)實(shí)例
} finally {
mIsInitializing = false;
if (success) {
// 打開成功
if (mDatabase != null) {
// 如果mDatabase有值則先關(guān)閉
try {
mDatabase.close();
} catch (Exception e) {
}
mDatabase.unlock();// 解鎖
}
mDatabase = db;// 賦值給mDatabase
} else {
// 打開失敗的情況:解鎖、關(guān)閉
if (mDatabase != null)
mDatabase.unlock();
if (db != null)
db.close();
}
}
}
大家可以看到,幾個(gè)關(guān)鍵步驟是,首先判斷mDatabase如果不為空已打開并不是只讀模式則直接返回,否則如果mDatabase不為空則加鎖,然后開始打開或創(chuàng)建數(shù)據(jù)庫(kù),比較版本,根據(jù)版本號(hào)來調(diào)用相應(yīng)的方法,為數(shù)據(jù)庫(kù)設(shè)置新版本號(hào),最后釋放舊的不為空的mDatabase并解鎖,把新打開的數(shù)據(jù)庫(kù)實(shí)例賦予mDatabase,并返回最新實(shí)例。
看完上面的過程之后,大家或許就清楚了許多,如果不是在遇到磁盤空間已滿等情況,getReadableDatabase()一般都會(huì)返回和getWritableDatabase()一樣的數(shù)據(jù)庫(kù)實(shí)例,所以我們?cè)贒BManager構(gòu)造方法中使用getWritableDatabase()獲取整個(gè)應(yīng)用所使用的數(shù)據(jù)庫(kù)實(shí)例是可行的。當(dāng)然如果你真的擔(dān)心這種情況會(huì)發(fā)生,那么你可以先用getWritableDatabase()獲取數(shù)據(jù)實(shí)例,如果遇到異常,再試圖用getReadableDatabase()獲取實(shí)例,當(dāng)然這個(gè)時(shí)候你獲取的實(shí)例只能讀不能寫了
最后,讓我們看一下如何使用這些數(shù)據(jù)操作方法來顯示數(shù)據(jù),界面核心邏輯代碼:
public class SQLiteActivity extends Activity {
public DiaryDao diaryDao;
//因?yàn)間etWritableDatabase內(nèi)部調(diào)用了mContext.openOrCreateDatabase(mName, 0, mFactory);
//所以要確保context已初始化,我們可以把實(shí)例化Dao的步驟放在Activity的onCreate里
@Override
protected void onCreate(Bundle savedInstanceState) {
diaryDao = new DiaryDao(SQLiteActivity.this);
initDatabase();
}
class ViewOcl implements View.OnClickListener {
@Override
public void onClick(View v) {
String strSQL;
boolean flag;
String message;
switch (v.getId()) {
case R.id.btnAdd:
String title = txtTitle.getText().toString().trim();
String weather = txtWeather.getText().toString().trim();;
String context = txtContext.getText().toString().trim();;
String publish = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date());
// 動(dòng)態(tài)組件SQL語(yǔ)句
strSQL = "insert into diary values(null,'" + title + "','"
+ weather + "','" + context + "','" + publish + "')";
flag = diaryDao.execOther(strSQL);
//返回信息
message = flag?"添加成功":"添加失敗";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
break;
case R.id.btnDelete:
strSQL = "delete from diary where tid = 1";
flag = diaryDao.execOther(strSQL);
//返回信息
message = flag?"刪除成功":"刪除失敗";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
break;
case R.id.btnQuery:
strSQL = "select * from diary order by publish desc";
String data = diaryDao.execQuery(strSQL);
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
break;
case R.id.btnUpdate:
strSQL = "update diary set title = '測(cè)試標(biāo)題1-1' where tid = 1";
flag = diaryDao.execOther(strSQL);
//返回信息
message = flag?"更新成功":"更新失敗";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
break;
}
}
}
private void initDatabase() {
// 創(chuàng)建數(shù)據(jù)庫(kù)對(duì)象
SqliteDBHelper sqliteDBHelper = new SqliteDBHelper(SQLiteActivity.this);
sqliteDBHelper.getWritableDatabase();
System.out.println("數(shù)據(jù)庫(kù)創(chuàng)建成功");
}
}
Android sqlite3數(shù)據(jù)庫(kù)管理工具
Android SDK的tools目錄下提供了一個(gè)sqlite3.exe工具,這是一個(gè)簡(jiǎn)單的sqlite數(shù)據(jù)庫(kù)管理工具。開發(fā)者可以方便的使用其對(duì)sqlite數(shù)據(jù)庫(kù)進(jìn)行命令行的操作。
程序運(yùn)行生成的*.db文件一般位于"/data/data/項(xiàng)目名(包括所處包名)/databases/*.db",因此要對(duì)數(shù)據(jù)庫(kù)文件進(jìn)行操作需要先找到數(shù)據(jù)庫(kù)文件:
1、進(jìn)入shell 命令
adb shell
2、找到數(shù)據(jù)庫(kù)文件
#cd data/data
#ls --列出所有項(xiàng)目
#cd project_name --進(jìn)入所需項(xiàng)目名
#cd databases
#ls --列出現(xiàn)寸的數(shù)據(jù)庫(kù)文件
3、進(jìn)入數(shù)據(jù)庫(kù)
#sqlite3 test_db --進(jìn)入所需數(shù)據(jù)庫(kù)
會(huì)出現(xiàn)類似如下字樣:
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
至此,可對(duì)數(shù)據(jù)庫(kù)進(jìn)行sql操作。
4、sqlite常用命令
>.databases --產(chǎn)看當(dāng)前數(shù)據(jù)庫(kù)
>.tables --查看當(dāng)前數(shù)據(jù)庫(kù)中的表
>.help --sqlite3幫助
>.schema --各個(gè)表的生成語(yǔ)句
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- 如何獲取Android設(shè)備掛載的所有存儲(chǔ)器
- android中使用SharedPreferences進(jìn)行數(shù)據(jù)存儲(chǔ)的操作方法
- Android調(diào)用相機(jī)并將照片存儲(chǔ)到sd卡上實(shí)現(xiàn)方法
- Android App將數(shù)據(jù)寫入內(nèi)部存儲(chǔ)和外部存儲(chǔ)的示例
- Android 數(shù)據(jù)存儲(chǔ)方式有哪幾種
- Android7.0版本影響開發(fā)的改進(jìn)分析
- Android 7.0新特性詳解
- 詳解Android 7.0 Settings 加載選項(xiàng)
- Android 7.0中拍照和圖片裁剪適配的問題詳解
- Android 7.0調(diào)用相機(jī)崩潰詳解及解決辦法
- Android 7.0 Nougat不得不知的11項(xiàng)新功能
- Android 7.0開發(fā)獲取存儲(chǔ)設(shè)備信息的方法
相關(guān)文章
Android onActivityResult和setResult方法詳解及使用
這篇文章主要介紹了Android onActivityResult和setResult方法詳解及使用的相關(guān)資料,這里提供實(shí)例,幫助大家學(xué)習(xí)理解,需要的朋友可以參考下2016-12-12
Android使用google breakpad捕獲分析native cash
這篇文章主要介紹了Android使用google breakpad捕獲分析native cash 的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
Android開發(fā)實(shí)現(xiàn)ListView部分布局監(jiān)聽的方法
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)ListView部分布局監(jiān)聽的方法,結(jié)合實(shí)例形式分析了Android通過設(shè)置tag標(biāo)志位實(shí)現(xiàn)ListView部分布局監(jiān)聽的相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
Android實(shí)現(xiàn)去哪兒攜程地址互換效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)去哪兒攜程地址互換效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
Android?adb?shell?dumpsys?audio?信息查看分析詳解
文章詳細(xì)介紹了如何使用dumpsysaudio命令查看和分析Android設(shè)備的音頻信息,包括音頻流狀態(tài)、音量、外設(shè)連接情況等,文章還提供了示例日志分析和源碼鏈接,幫助開發(fā)者更好地理解和調(diào)試Android音頻系統(tǒng)2024-11-11
Android 圖片存儲(chǔ)到指定路徑和相冊(cè)的方法
本篇文章主要介紹了Android 圖片存儲(chǔ)到指定路徑和相冊(cè)的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Android動(dòng)畫 實(shí)現(xiàn)開關(guān)按鈕動(dòng)畫(屬性動(dòng)畫之平移動(dòng)畫)實(shí)例代碼
這篇文章主要介紹了Android動(dòng)畫 實(shí)現(xiàn)開關(guān)按鈕動(dòng)畫(屬性動(dòng)畫之平移動(dòng)畫)實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-11-11
Android 標(biāo)準(zhǔn)Intent的使用詳解
這篇文章主要介紹了Android 標(biāo)準(zhǔn)Intent的使用詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03

