Android編程中的5種數(shù)據(jù)存儲方式
本文介紹Android平臺進行數(shù)據(jù)存儲的五大方式,分別如下:
1 使用SharedPreferences存儲數(shù)據(jù)
2 文件存儲數(shù)據(jù)
3 SQLite數(shù)據(jù)庫存儲數(shù)據(jù)
4 使用ContentProvider存儲數(shù)據(jù)
5 網(wǎng)絡(luò)存儲數(shù)據(jù)
下面詳細講解這五種方式的特點
第一種: 使用SharedPreferences存儲數(shù)據(jù)
適用范圍:保存少量的數(shù)據(jù),且這些數(shù)據(jù)的格式非常簡單:字符串型、基本類型的值。比如應(yīng)用程序的各種配置信息(如是否打開音效、是否使用震動效果、小游戲的玩家積分等),解鎖口 令密碼等
核心原理:保存基于XML文件存儲的key-value鍵值對數(shù)據(jù),通常用來存儲一些簡單的配置信息。通過DDMS的File Explorer面板,展開文件瀏覽樹,很明顯SharedPreferences數(shù)據(jù)總是存儲在/data/data/<package name>/shared_prefs目錄下。SharedPreferences對象本身只能獲取數(shù)據(jù)而不支持存儲和修改,存儲修改是通過SharedPreferences.edit()獲取的內(nèi)部接口Editor對象實現(xiàn)。 SharedPreferences本身是一 個接口,程序無法直接創(chuàng)建SharedPreferences實例,只能通過Context提供的getSharedPreferences(String name, int mode)方法來獲取SharedPreferences實例,該方法中name表示要操作的xml文件名,第二個參數(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對應(yīng)的數(shù)據(jù),其中xxx 可以是boolean,float,int等各種基本類型據(jù)
SharedPreferences.Editor remove(): 刪除SharedPreferences中指定key對應(yīng)的數(shù)據(jù)項
boolean commit(): 當Editor編輯完成后,使用該方法提交修改
實際案例:運行界面如下
這里只提供了兩個按鈕和一個輸入文本框,布局簡單,故在此不給出界面布局文件了,程序核心代碼如下:
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)建一個SharedPreferences.Editor接口對象,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)建一個SharedPreferences接口對象 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時,指定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獲取對應(yīng)的SharedPreferences
SharedPreferences read = pvCount.getSharedPreferences("lock", Context.MODE_WORLD_READABLE);
4、如果是寫入數(shù)據(jù),使用Editor接口即可,所有其他操作均和前面一致。
SharedPreferences對象與SQLite數(shù)據(jù)庫相比,免去了創(chuàng)建數(shù)據(jù)庫,創(chuàng)建表,寫SQL語句等諸多操作,相對而言更加方便,簡潔。但是SharedPreferences也有其自身缺陷,比如其職能存儲boolean,int,float,long和String五種簡單的數(shù)據(jù)類型,比如其無法進行條件查詢等。所以不論SharedPreferences的數(shù)據(jù)存儲操作是如何簡單,它也只能是存儲方式的一種補充,而無法完全替代如SQLite數(shù)據(jù)庫這樣的其他數(shù)據(jù)存儲方式。
第二種: 文件存儲數(shù)據(jù)
核心原理: Context提供了兩個方法來打開數(shù)據(jù)文件里的文件IO流 FileInputStream openFileInput(String name); FileOutputStream(String name , int mode),這兩個方法第一個參數(shù) 用于指定文件名,第二個參數(shù)指定打開文件的模式。具體有以下值可選:
MODE_PRIVATE:為默認操作模式,代表該文件是私有數(shù)據(jù),只能被應(yīng)用本身訪問,在該模式下,寫入的內(nèi)容會覆蓋原文件的內(nèi)容,如果想把新寫入的內(nèi)容追加到原文件中???nbsp; 以使用Context.MODE_APPEND
MODE_APPEND:模式會檢查文件是否存在,存在就往文件追加內(nèi)容,否則就創(chuàng)建新文件。
MODE_WORLD_READABLE:表示當前文件可以被其他應(yīng)用讀?。?br />
MODE_WORLD_WRITEABLE:表示當前文件可以被其他應(yīng)用寫入。
除此之外,Context還提供了如下幾個重要的方法:
getDir(String name , int mode):在應(yīng)用程序的數(shù)據(jù)文件夾下獲取或者創(chuàng)建name對應(yīng)的子目錄
File getFilesDir():獲取該應(yīng)用程序的數(shù)據(jù)文件夾得絕對路徑
String[] fileList():返回該應(yīng)用數(shù)據(jù)文件夾的全部文件
實際案例:界面沿用上圖
核心代碼如下:
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)建一個FileOutputStream對象,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 會自動創(chuàng)建它。創(chuàng)建的文件保存在/data/data/<package name>/files目錄,如: /data/data/cn.tony.app/files/message.txt,
下面講解某些特殊文件讀寫需要注意的地方:
讀寫sdcard上的文件
其中讀寫步驟按如下進行:
1、調(diào)用Environment的getExternalStorageState()方法判斷手機上是否插了sd卡,且應(yīng)用程序具有讀寫SD卡的權(quán)限,如下代碼將返回true
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
2、調(diào)用Environment.getExternalStorageDirectory()方法來獲取外部存儲器,也就是SD卡的目錄,或者使用"/mnt/sdcard/"目錄
3、使用IO流操作SD卡上的文件
注意點:手機應(yīng)該已插入SD卡,對于模擬器而言,可通過mksdcard命令來創(chuàng)建虛擬存儲卡
必須在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類對象 if (!file.getParentFile().exists()) { // 父文件夾不存在 file.getParentFile().mkdirs(); // 創(chuàng)建文件夾 } PrintStream out = null; // 打印流對象用于輸出 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類對象 if (!file.getParentFile().exists()) { // 父文件夾不存在 file.getParentFile().mkdirs(); // 創(chuàng)建文件夾 } Scanner scan = null; // 掃描輸入 StringBuilder sb = new StringBuilder(); try { scan = new Scanner(new FileInputStream(file)); // 實例化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存儲數(shù)據(jù)
SQLite是輕量級嵌入式數(shù)據(jù)庫引擎,它支持 SQL 語言,并且只利用很少的內(nèi)存就有很好的性能?,F(xiàn)在的主流移動設(shè)備像Android、iPhone等都使用SQLite作為復雜數(shù)據(jù)的存儲引擎,在我們?yōu)橐苿釉O(shè)備開發(fā)應(yīng)用程序時,也許就要使用到SQLite來存儲我們大量的數(shù)據(jù),所以我們就需要掌握移動設(shè)備上的SQLite開發(fā)技巧
SQLiteDatabase類為我們提供了很多種方法,上面的代碼中基本上囊括了大部分的數(shù)據(jù)庫操作;對于添加、更新和刪除來說,我們都可以使用
db.executeSQL(String sql); db.executeSQL(String sql, Object[] bindArgs); //sql語句中使用占位符,然后第二個參數(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);
以上三個方法的第一個參數(shù)都是表示要操作的表名;insert中的第二個參數(shù)表示如果插入的數(shù)據(jù)每一列都為空的話,需要指定此行中某一列的名稱,系統(tǒng)將此列設(shè)置為NULL,不至于出現(xiàn)錯誤;insert中的第三個參數(shù)是ContentValues類型的變量,是鍵值對組成的Map,key代表列名,value代表該列要插入的值;update的第二個參數(shù)也很類似,只不過它是更新該字段key為最新的value值,第三個參數(shù)whereClause表示W(wǎng)HERE表達式,比如“age > ? and age < ?”等,最后的whereArgs參數(shù)是占位符的實際參數(shù)值;delete方法的參數(shù)也是一樣
下面給出demo
數(shù)據(jù)的添加
1.使用insert方法
ContentValues cv = new ContentValues();//實例化一個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方式來實現(xiàn)
String sql = "insert into user(username,password) values ('Jack Johnson','iLovePopMuisc');//插入操作的SQL語句 db.execSQL(sql);//執(zhí)行SQL語句
數(shù)據(jù)的刪除
同樣有2種方式可以實現(xiàn)
String whereClause = "username=?";//刪除的條件 String[] whereArgs = {"Jack Johnson"};//刪除的條件參數(shù) db.delete("user",whereClause,whereArgs);//執(zhí)行刪除
使用execSQL方式的實現(xiàn)
String sql = "delete from user where username='Jack Johnson'";//刪除操作的SQL語句 db.execSQL(sql);//執(zhí)行刪除操作
數(shù)據(jù)修改
同上,仍是2種方式
ContentValues cv = new ContentValues();//實例化ContentValues cv.put("password","iHatePopMusic");//添加要更改的字段及內(nèi)容 String whereClause = "username=?";//修改條件 String[] whereArgs = {"Jack Johnson"};//修改條件的參數(shù) db.update("user",cv,whereClause,whereArgs);//執(zhí)行修改
使用execSQL方式的實現(xiàn)
String sql = "update user set password = 'iHatePopMusic' where username='Jack Johnson'";//修改的SQL語句 db.execSQL(sql);//執(zhí)行修改
數(shù)據(jù)查詢
下面來說說查詢操作。查詢操作相對于上面的幾種操作要復雜些,因為我們經(jīng)常要面對著各種各樣的查詢條件,所以系統(tǒng)也考慮到這種復雜性,為我們提供了較為豐富的查詢形式:
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);
上面幾種都是常用的查詢方法,第一種最為簡單,將所有的SQL語句都組織到一個字符串中,使用占位符代替實際參數(shù),selectionArgs就是占位符實際參數(shù)集;
各參數(shù)說明:
table:表名稱
colums:表示要查詢的列所有名稱集
selection:表示W(wǎng)HERE之后的條件語句,可以使用占位符
selectionArgs:條件語句的參數(shù)數(shù)組
groupBy:指定分組的列名
having:指定分組條件,配合groupBy使用
orderBy:y指定排序的列名
limit:指定分頁參數(shù)
distinct:指定“true”或“false”表示要不要過濾重復值
Cursor:返回值,相當于結(jié)果集ResultSet
最后,他們同時返回一個Cursor對象,代表數(shù)據(jù)集的游標,有點類似于JavaSE中的ResultSet。下面是Cursor對象的常用方法:
c.move(int offset); //以當前位置為參考,移動到指定行 c.moveToFirst(); //移動到第一行 c.moveToLast(); //移動到最后一行 c.moveToPosition(int position); //移動到指定行 c.moveToPrevious(); //移動到前一行 c.moveToNext(); //移動到下一行 c.isFirst(); //是否指向第一條 c.isLast(); //是否指向最后一條 c.isBeforeFirst(); //是否指向第一條之前 c.isAfterLast(); //是否指向最后一條之后 c.isNull(int columnIndex); //指定列是否為空(列基數(shù)為0) c.isClosed(); //游標是否已關(guān)閉 c.getCount(); //總數(shù)據(jù)項數(shù) c.getPosition(); //返回當前游標所指向的行數(shù) c.getColumnIndex(String columnName);//返回某列名對應(yīng)的列索引值 c.getString(int columnIndex); //返回當前行指定列的值
實現(xiàn)代碼
String[] params = {12345,123456}; Cursor cursor = db.query("user",columns,"ID=?",params,null,null,null);//查詢并獲得游標 if(cursor.moveToFirst()){//判斷游標是否為空 for(int i=0;i<cursor.getCount();i++){ cursor.move(i);//移動到指定記錄 String username = cursor.getString(cursor.getColumnIndex("username"); String password = cursor.getString(cursor.getColumnIndex("password")); } }
通過rawQuery實現(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)用到了這幾個常用方法中的一些,關(guān)于更多的信息,大家可以參考官方文檔中的說明。
最后當我們完成了對數(shù)據(jù)庫的操作后,記得調(diào)用SQLiteDatabase的close()方法釋放數(shù)據(jù)庫連接,否則容易出現(xiàn)SQLiteException。
上面就是SQLite的基本應(yīng)用,但在實際開發(fā)中,為了能夠更好的管理和維護數(shù)據(jù)庫,我們會封裝一個繼承自SQLiteOpenHelper類的數(shù)據(jù)庫操作類,然后以這個類為基礎(chǔ),再封裝我們的業(yè)務(wù)邏輯方法。
這里直接使用案例講解:下面是案例demo的界面
SQLiteOpenHelper類介紹
SQLiteOpenHelper是SQLiteDatabase的一個幫助類,用來管理數(shù)據(jù)庫的創(chuàng)建和版本的更新。一般是建立一個類繼承它,并實現(xiàn)它的onCreate和onUpgrade方法。
方法名 | 方法描述 |
---|---|
SQLiteOpenHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version) |
構(gòu)造方法,其中 context 程序上下文環(huán)境 即:XXXActivity.this; name :數(shù)據(jù)庫名字; factory:游標工廠,默認為null,即為使用默認工廠; version 數(shù)據(jù)庫版本號 |
onCreate(SQLiteDatabase db) | 創(chuàng)建數(shù)據(jù)庫時調(diào)用 |
onUpgrade(SQLiteDatabase db,int oldVersion , int newVersion) | 版本更新時調(diào)用 |
getReadableDatabase() | 創(chuàng)建或打開一個只讀數(shù)據(jù)庫 |
getWritableDatabase() | 創(chuàng)建或打開一個讀寫數(shù)據(jù)庫 |
首先創(chuàng)建數(shù)據(jù)庫類
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ù)庫名字 * factory 接收數(shù)據(jù),一般情況為null * version 數(shù)據(jù)庫版本號 */ public SqliteDBHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } //數(shù)據(jù)庫第一次被創(chuàng)建時,onCreate()會被調(diào)用 @Override public void onCreate(SQLiteDatabase db) { // 步驟3:數(shù)據(jù)庫表的創(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)建對象 db.execSQL(strSQL); } //數(shù)據(jù)庫版本變化時,會調(diào)用onUpgrade() @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { } }
正如上面所述,數(shù)據(jù)庫第一次創(chuàng)建時onCreate方法會被調(diào)用,我們可以執(zhí)行創(chuàng)建表的語句,當系統(tǒng)發(fā)現(xiàn)版本變化之后,會調(diào)用onUpgrade方法,我們可以執(zhí)行修改表結(jié)構(gòu)等語句。
我們需要一個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相當于JDBC中的ResultSet Cursor cursor = db.rawQuery(strSQL, null); // 始終讓cursor指向數(shù)據(jù)庫表的第1行記錄 cursor.moveToFirst(); // 定義一個StringBuffer的對象,用于動態(tài)拼接字符串 StringBuffer sb = new StringBuffer(); // 循環(huán)游標,如果不是最后一項記錄 while (!cursor.isAfterLast()) { sb.append(cursor.getInt(0) + "/" + cursor.getString(1) + "/" + cursor.getString(2) + "/" + cursor.getString(3) + "/" + cursor.getString(4)+"#"); //cursor游標移動 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ù) } } }
我們在Dao構(gòu)造方法中實例化sqliteDBHelper并獲取一個SQLiteDatabase對象,作為整個應(yīng)用的數(shù)據(jù)庫實例;在增刪改信息時,我們采用了事務(wù)處理,確保數(shù)據(jù)完整性;最后要注意釋放數(shù)據(jù)庫資源db.close(),這一個步驟在我們整個應(yīng)用關(guān)閉時執(zhí)行,這個環(huán)節(jié)容易被忘記,所以朋友們要注意。
我們獲取數(shù)據(jù)庫實例時使用了getWritableDatabase()方法,也許朋友們會有疑問,在getWritableDatabase()和getReadableDatabase()中,你為什么選擇前者作為整個應(yīng)用的數(shù)據(jù)庫實例呢?在這里我想和大家著重分析一下這一點。
我們來看一下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ù)據(jù)庫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ù)庫 則以只讀方式打開 SQLiteDatabase db = null; try { mIsInitializing = true; String path = mContext.getDatabasePath(mName).getPath();// 獲取數(shù)據(jù)庫路徑 // 以只讀方式打開數(shù)據(jù)庫 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ù)庫 return mDatabase;// 返回打開的數(shù)據(jù)庫 } finally { mIsInitializing = false; if (db != null && db != mDatabase) db.close(); } }
在getReadableDatabase()方法中,首先判斷是否已存在數(shù)據(jù)庫實例并且是打開狀態(tài),如果是,則直接返回該實例,否則試圖獲取一個可讀寫模式的數(shù)據(jù)庫實例,如果遇到磁盤空間已滿等情況獲取失敗的話,再以只讀模式打開數(shù)據(jù)庫,獲取數(shù)據(jù)庫實例并返回,然后為mDatabase賦值為最新打開的數(shù)據(jù)庫實例。既然有可能調(diào)用到getWritableDatabase()方法,我們就要看一下了:
public synchronized SQLiteDatabase getWritableDatabase() { if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) { // 如果mDatabase不為空已打開并且不是只讀模式 則返回該實例 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ù)庫 db = mContext.openOrCreateDatabase(mName, 0, mFactory); } // 獲取數(shù)據(jù)庫版本(如果剛創(chuàng)建的數(shù)據(jù)庫,版本為0) int version = db.getVersion(); // 比較版本(我們代碼中的版本mNewVersion為1) if (version != mNewVersion) { db.beginTransaction();// 開始事務(wù) try { if (version == 0) { // 執(zhí)行我們的onCreate方法 onCreate(db); } else { // 如果我們應(yīng)用升級了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ù)庫實例 } 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(); } } }
大家可以看到,幾個關(guān)鍵步驟是,首先判斷mDatabase如果不為空已打開并不是只讀模式則直接返回,否則如果mDatabase不為空則加鎖,然后開始打開或創(chuàng)建數(shù)據(jù)庫,比較版本,根據(jù)版本號來調(diào)用相應(yīng)的方法,為數(shù)據(jù)庫設(shè)置新版本號,最后釋放舊的不為空的mDatabase并解鎖,把新打開的數(shù)據(jù)庫實例賦予mDatabase,并返回最新實例。
看完上面的過程之后,大家或許就清楚了許多,如果不是在遇到磁盤空間已滿等情況,getReadableDatabase()一般都會返回和getWritableDatabase()一樣的數(shù)據(jù)庫實例,所以我們在DBManager構(gòu)造方法中使用getWritableDatabase()獲取整個應(yīng)用所使用的數(shù)據(jù)庫實例是可行的。當然如果你真的擔心這種情況會發(fā)生,那么你可以先用getWritableDatabase()獲取數(shù)據(jù)實例,如果遇到異常,再試圖用getReadableDatabase()獲取實例,當然這個時候你獲取的實例只能讀不能寫了
最后,讓我們看一下如何使用這些數(shù)據(jù)操作方法來顯示數(shù)據(jù),界面核心邏輯代碼:
public class SQLiteActivity extends Activity { public DiaryDao diaryDao; //因為getWritableDatabase內(nèi)部調(diào)用了mContext.openOrCreateDatabase(mName, 0, mFactory); //所以要確保context已初始化,我們可以把實例化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()); // 動態(tài)組件SQL語句 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 = '測試標題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ù)庫對象 SqliteDBHelper sqliteDBHelper = new SqliteDBHelper(SQLiteActivity.this); sqliteDBHelper.getWritableDatabase(); System.out.println("數(shù)據(jù)庫創(chuàng)建成功"); } }
Android sqlite3數(shù)據(jù)庫管理工具
Android SDK的tools目錄下提供了一個sqlite3.exe工具,這是一個簡單的sqlite數(shù)據(jù)庫管理工具。開發(fā)者可以方便的使用其對sqlite數(shù)據(jù)庫進行命令行的操作。
程序運行生成的*.db文件一般位于"/data/data/項目名(包括所處包名)/databases/*.db",因此要對數(shù)據(jù)庫文件進行操作需要先找到數(shù)據(jù)庫文件:
1、進入shell 命令
adb shell
2、找到數(shù)據(jù)庫文件
#cd data/data
#ls --列出所有項目
#cd project_name --進入所需項目名
#cd databases
#ls --列出現(xiàn)寸的數(shù)據(jù)庫文件
3、進入數(shù)據(jù)庫
#sqlite3 test_db --進入所需數(shù)據(jù)庫
會出現(xiàn)類似如下字樣:
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
至此,可對數(shù)據(jù)庫進行sql操作。
4、sqlite常用命令
>.databases --產(chǎn)看當前數(shù)據(jù)庫
>.tables --查看當前數(shù)據(jù)庫中的表
>.help --sqlite3幫助
>.schema --各個表的生成語句
希望本文所述對大家Android程序設(shè)計有所幫助。
- 如何獲取Android設(shè)備掛載的所有存儲器
- android中使用SharedPreferences進行數(shù)據(jù)存儲的操作方法
- Android調(diào)用相機并將照片存儲到sd卡上實現(xiàn)方法
- Android App將數(shù)據(jù)寫入內(nèi)部存儲和外部存儲的示例
- Android 數(shù)據(jù)存儲方式有哪幾種
- Android7.0版本影響開發(fā)的改進分析
- Android 7.0新特性詳解
- 詳解Android 7.0 Settings 加載選項
- Android 7.0中拍照和圖片裁剪適配的問題詳解
- Android 7.0調(diào)用相機崩潰詳解及解決辦法
- Android 7.0 Nougat不得不知的11項新功能
- Android 7.0開發(fā)獲取存儲設(shè)備信息的方法
相關(guān)文章
Android使用AlertDialog實現(xiàn)的信息列表單選、多選對話框功能
在使用AlertDialog實現(xiàn)單選和多選對話框時,分別設(shè)置setSingleChoiceItems()和setMultiChoiceItems()函數(shù)。具體實現(xiàn)代碼大家參考下本文吧2017-03-03Android多種方式實現(xiàn)相機圓形預(yù)覽的示例代碼
這篇文章主要介紹了Android多種方式實現(xiàn)相機圓形預(yù)覽的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08Android實現(xiàn)圖片點擊預(yù)覽效果(zoom動畫)
本文主要介紹了Android實現(xiàn)圖片點擊預(yù)覽效果的方法步驟。具有很好的參考價值,下面跟著小編一起來看下吧2017-03-03Android獲取內(nèi)置sdcard跟外置sdcard路徑
這篇文章主要介紹了Android獲取內(nèi)置sdcard跟外置sdcard路徑的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09