本文介紹Android平臺進行數據存儲的五大方式,分別以下: html
1 使用SharedPreferences存儲數據python
2 文件存儲數據 android
5 網絡存儲數據數據庫
下面詳細講解這五種方式的特色數組
第一種: 使用SharedPreferences存儲數據網絡
適用範圍:保存少許的數據,且這些數據的格式很是簡單:字符串型、基本類型的值。好比應用程序的各類配置信息(如是否打開音效、是否使用震動效果、小遊戲的玩家積分等),解鎖口 令密碼等app
核心原理:保存基於XML文件存儲的key-value鍵值對數據,一般用來存儲一些簡單的配置信息。經過DDMS的File Explorer面板,展開文件瀏覽樹,很明顯SharedPreferences數據老是存儲在/data/data/<package name>/shared_prefs目錄下。SharedPreferences對象自己只能獲取數據而不支持存儲和修改,存儲修改是經過SharedPreferences.edit()獲取的內部接口Editor對象實現。 SharedPreferences自己是一 個接口,程序沒法直接建立SharedPreferences實例,只能經過Context提供的getSharedPreferences(String name, int mode)方法來獲取SharedPreferences實例,該方法中name表示要操做的xml文件名,第二個參數具體以下:ide
Context.MODE_PRIVATE: 指定該SharedPreferences數據只能被本應用程序讀、寫。
Context.MODE_WORLD_READABLE: 指定該SharedPreferences數據能被其餘應用程序讀,但不能寫。
Context.MODE_WORLD_WRITEABLE: 指定該SharedPreferences數據能被其餘應用程序讀,寫
Editor有以下主要重要方法:
SharedPreferences.Editor clear():清空SharedPreferences裏全部數據
SharedPreferences.Editor putXxx(String key , xxx value): 向SharedPreferences存入指定key對應的數據,其中xxx 能夠是boolean,float,int等各類基本類型據
SharedPreferences.Editor remove(): 刪除SharedPreferences中指定key對應的數據項
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:建立一個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(), "口令設置成功", Toast.LENGTH_LONG).show(); break; case R.id.btnGet: //步驟1:建立一個SharedPreferences接口對象 SharedPreferences read = getSharedPreferences("lock", MODE_WORLD_READABLE); //步驟2:獲取文件中的值 String value = read.getString("code", ""); Toast.makeText(getApplicationContext(), "口令爲:"+value, Toast.LENGTH_LONG).show(); break; } } }
讀寫其餘應用的SharedPreferences: 步驟以下
一、在建立SharedPreferences時,指定MODE_WORLD_READABLE模式,代表該SharedPreferences數據能夠被其餘程序讀取
二、建立其餘應用程序對應的Context:
Context pvCount = createPackageContext("com.tony.app", Context.CONTEXT_IGNORE_SECURITY);這裏的com.tony.app就是其餘程序的包名
三、使用其餘程序的Context獲取對應的SharedPreferences
SharedPreferences read = pvCount.getSharedPreferences("lock", Context.MODE_WORLD_READABLE);
四、若是是寫入數據,使用Editor接口便可,全部其餘操做均和前面一致。
SharedPreferences對象與SQLite數據庫相比,免去了建立數據庫,建立表,寫SQL語句等諸多操做,相對而言更加方便,簡潔。可是SharedPreferences也有其自身缺陷,好比其職能存儲boolean,int,float,long和String五種簡單的數據類型,好比其沒法進行條件查詢等。因此不論SharedPreferences的數據存儲操做是如何簡單,它也只能是存儲方式的一種補充,而沒法徹底替代如SQLite數據庫這樣的其餘數據存儲方式。
第二種: 文件存儲數據
核心原理: Context提供了兩個方法來打開數據文件裏的文件IO流 FileInputStream openFileInput(String name); FileOutputStream(String name , int mode),這兩個方法第一個參數 用於指定文件名,第二個參數指定打開文件的模式。具體有如下值可選:
MODE_PRIVATE:爲默認操做模式,表明該文件是私有數據,只能被應用自己訪問,在該模式下,寫入的內容會覆蓋原文件的內容,若是想把新寫入的內容追加到原文件中。可 以使用Context.MODE_APPEND
MODE_APPEND:模式會檢查文件是否存在,存在就往文件追加內容,不然就建立新文件。
MODE_WORLD_READABLE:表示當前文件能夠被其餘應用讀取;
MODE_WORLD_WRITEABLE:表示當前文件能夠被其餘應用寫入。
除此以外,Context還提供了以下幾個重要的方法:
getDir(String name , int mode):在應用程序的數據文件夾下獲取或者建立name對應的子目錄
File getFilesDir():獲取該應用程序的數據文件夾得絕對路徑
String[] fileList():返回該應用數據文件夾的所有文件
實際案例:界面沿用上圖
核心代碼以下:
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:建立一個FileOutputStream對象,MODE_APPEND追加模式 FileOutputStream fos = openFileOutput("message.txt", MODE_APPEND); // 步驟3:將獲取過來的值放入文件 fos.write(msg.getBytes()); // 步驟4:關閉數據流 fos.close(); } catch (Exception e) { e.printStackTrace(); } }
openFileOutput()方法的第一參數用於指定文件名稱,不能包含路徑分隔符「/」 ,若是文件不存在,Android 會自動建立它。建立的文件保存在/data/data/<package name>/files目錄,如: /data/data/cn.tony.app/files/message.txt,
下面講解某些特殊文件讀寫須要注意的地方:
讀寫sdcard上的文件
其中讀寫步驟按以下進行:
一、調用Environment的getExternalStorageState()方法判斷手機上是否插了sd卡,且應用程序具備讀寫SD卡的權限,以下代碼將返回true
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
二、調用Environment.getExternalStorageDirectory()方法來獲取外部存儲器,也就是SD卡的目錄,或者使用"/mnt/sdcard/"目錄
三、使用IO流操做SD卡上的文件
注意點:手機應該已插入SD卡,對於模擬器而言,可經過mksdcard命令來建立虛擬存儲卡
必須在AndroidManifest.xml上配置讀寫SD卡的權限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
案例代碼:
// 文件寫操做函數 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(); // 建立文件夾 } 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(); // 關閉打印流 } } } else { // SDCard不存在,使用Toast提示用戶 Toast.makeText(this, "保存失敗,SD卡不存在!", Toast.LENGTH_LONG).show(); } } // 文件讀操做函數 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(); // 建立文件夾 } Scanner scan = null; // 掃描輸入 StringBuilder sb = new StringBuilder(); try { scan = new Scanner(new FileInputStream(file)); // 實例化Scanner while (scan.hasNext()) { // 循環讀取 sb.append(scan.next() + "\n"); // 設置文本 } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (scan != null) { scan.close(); // 關閉打印流 } } } else { // SDCard不存在,使用Toast提示用戶 Toast.makeText(this, "讀取失敗,SD卡不存在!", Toast.LENGTH_LONG).show(); } return null; }
第三種:SQLite存儲數據
SQLite是輕量級嵌入式數據庫引擎,它支持 SQL 語言,而且只利用不多的內存就有很好的性能。如今的主流移動設備像Android、iPhone等都使用SQLite做爲複雜數據的存儲引擎,在咱們爲移動設備開發應用程序時,也許就要使用到SQLite來存儲咱們大量的數據,因此咱們就須要掌握移動設備上的SQLite開發技巧
SQLiteDatabase類爲咱們提供了不少種方法,上面的代碼中基本上囊括了大部分的數據庫操做;對於添加、更新和刪除來講,咱們均可以使用
1 db.executeSQL(String sql); 2 db.executeSQL(String sql, Object[] bindArgs);//sql語句中使用佔位符,而後第二個參數是實際的參數集
除了統一的形式以外,他們還有各自的操做方法:
1 db.insert(String table, String nullColumnHack, ContentValues values); 2 db.update(String table, Contentvalues values, String whereClause, String whereArgs); 3 db.delete(String table, String whereClause, String whereArgs);
以上三個方法的第一個參數都是表示要操做的表名;insert中的第二個參數表示若是插入的數據每一列都爲空的話,須要指定此行中某一列的名稱,系統將此列設置爲NULL,不至於出現錯誤;insert中的第三個參數是ContentValues類型的變量,是鍵值對組成的Map,key表明列名,value表明該列要插入的值;update的第二個參數也很相似,只不過它是更新該字段key爲最新的value值,第三個參數whereClause表示WHERE表達式,好比「age > ? and age < ?」等,最後的whereArgs參數是佔位符的實際參數值;delete方法的參數也是同樣
下面給出demo
數據的添加
1.使用insert方法
1 ContentValues cv = new ContentValues();//實例化一個ContentValues用來裝載待插入的數據 2 cv.put("title","you are beautiful");//添加title 3 cv.put("weather","sun"); //添加weather 4 cv.put("context","xxxx"); //添加context 5 String publish = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") 6 .format(new Date()); 7 cv.put("publish ",publish); //添加publish 8 db.insert("diary",null,cv);//執行插入操做
2.使用execSQL方式來實現
String sql = "insert into user(username,password) values ('Jack Johnson','iLovePopMuisc');//插入操做的SQL語句 db.execSQL(sql);//執行SQL語句
數據的刪除
一樣有2種方式能夠實現
String whereClause = "username=?";//刪除的條件 String[] whereArgs = {"Jack Johnson"};//刪除的條件參數 db.delete("user",whereClause,whereArgs);//執行刪除
使用execSQL方式的實現
String sql = "delete from user where username='Jack Johnson'";//刪除操做的SQL語句 db.execSQL(sql);//執行刪除操做
數據修改
同上,還是2種方式
ContentValues cv = new ContentValues();//實例化ContentValues cv.put("password","iHatePopMusic");//添加要更改的字段及內容 String whereClause = "username=?";//修改條件 String[] whereArgs = {"Jack Johnson"};//修改條件的參數 db.update("user",cv,whereClause,whereArgs);//執行修改
使用execSQL方式的實現
String sql = "update user set password = 'iHatePopMusic' where username='Jack Johnson'";//修改的SQL語句 db.execSQL(sql);//執行修改
數據查詢
下面來講說查詢操做。查詢操做相對於上面的幾種操做要複雜些,由於咱們常常要面對着各類各樣的查詢條件,因此係統也考慮到這種複雜性,爲咱們提供了較爲豐富的查詢形式:
1 db.rawQuery(String sql, String[] selectionArgs); 2 db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy); 3 db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit); 4 db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
上面幾種都是經常使用的查詢方法,第一種最爲簡單,將全部的SQL語句都組織到一個字符串中,使用佔位符代替實際參數,selectionArgs就是佔位符實際參數集;
各參數說明:
最後,他們同時返回一個Cursor對象,表明數據集的遊標,有點相似於JavaSE中的ResultSet。下面是Cursor對象的經常使用方法:
1 c.move(int offset); //以當前位置爲參考,移動到指定行 2 c.moveToFirst(); //移動到第一行 3 c.moveToLast(); //移動到最後一行 4 c.moveToPosition(int position); //移動到指定行 5 c.moveToPrevious(); //移動到前一行 6 c.moveToNext(); //移動到下一行 7 c.isFirst(); //是否指向第一條 8 c.isLast(); //是否指向最後一條 9 c.isBeforeFirst(); //是否指向第一條以前 10 c.isAfterLast(); //是否指向最後一條以後 11 c.isNull(int columnIndex); //指定列是否爲空(列基數爲0) 12 c.isClosed(); //遊標是否已關閉 13 c.getCount(); //總數據項數 14 c.getPosition(); //返回當前遊標所指向的行數 15 c.getColumnIndex(String columnName);//返回某列名對應的列索引值 16 c.getString(int columnIndex); //返回當前行指定列的值
實現代碼
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實現的帶參數查詢
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();
在上面的代碼示例中,已經用到了這幾個經常使用方法中的一些,關於更多的信息,你們能夠參考官方文檔中的說明。
最後當咱們完成了對數據庫的操做後,記得調用SQLiteDatabase的close()方法釋放數據庫鏈接,不然容易出現SQLiteException。
上面就是SQLite的基本應用,但在實際開發中,爲了可以更好的管理和維護數據庫,咱們會封裝一個繼承自SQLiteOpenHelper類的數據庫操做類,而後以這個類爲基礎,再封裝咱們的業務邏輯方法。
這裏直接使用案例講解:下面是案例demo的界面
SQLiteOpenHelper類介紹
SQLiteOpenHelper是SQLiteDatabase的一個幫助類,用來管理數據庫的建立和版本的更新。通常是創建一個類繼承它,並實現它的onCreate和onUpgrade方法。
方法名 | 方法描述 |
---|---|
SQLiteOpenHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version) | 構造方法,其中 context 程序上下文環境 即:XXXActivity.this; name :數據庫名字; factory:遊標工廠,默認爲null,即爲使用默認工廠; version 數據庫版本號 |
onCreate(SQLiteDatabase db) | 建立數據庫時調用 |
onUpgrade(SQLiteDatabase db,int oldVersion , int newVersion) | 版本更新時調用 |
getReadableDatabase() | 建立或打開一個只讀數據庫 |
getWritableDatabase() | 建立或打開一個讀寫數據庫 |
首先建立數據庫類
1 import android.content.Context; 2 import android.database.sqlite.SQLiteDatabase; 3 import android.database.sqlite.SQLiteDatabase.CursorFactory; 4 import android.database.sqlite.SQLiteOpenHelper; 5 6 public class SqliteDBHelper extends SQLiteOpenHelper { 7 8 // 步驟1:設置常數參量 9 private static final String DATABASE_NAME = "diary_db"; 10 private static final int VERSION = 1; 11 private static final String TABLE_NAME = "diary"; 12 13 // 步驟2:重載構造方法 14 public SqliteDBHelper(Context context) { 15 super(context, DATABASE_NAME, null, VERSION); 16 } 17 18 /* 19 * 參數介紹:context 程序上下文環境 即:XXXActivity.this 20 * name 數據庫名字 21 * factory 接收數據,通常狀況爲null 22 * version 數據庫版本號 23 */ 24 public SqliteDBHelper(Context context, String name, CursorFactory factory, 25 int version) { 26 super(context, name, factory, version); 27 } 28 //數據庫第一次被建立時,onCreate()會被調用 29 @Override 30 public void onCreate(SQLiteDatabase db) { 31 // 步驟3:數據庫表的建立 32 String strSQL = "create table " 33 + TABLE_NAME 34 + "(tid integer primary key autoincrement,title varchar(20),weather varchar(10),context text,publish date)"; 35 //步驟4:使用參數db,建立對象 36 db.execSQL(strSQL); 37 } 38 //數據庫版本變化時,會調用onUpgrade() 39 @Override 40 public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { 41 42 } 43 }
正如上面所述,數據庫第一次建立時onCreate方法會被調用,咱們能夠執行建立表的語句,當系統發現版本變化以後,會調用onUpgrade方法,咱們能夠執行修改表結構等語句。
咱們須要一個Dao,來封裝咱們全部的業務方法,代碼以下:
1 import android.content.Context; 2 import android.database.Cursor; 3 import android.database.sqlite.SQLiteDatabase; 4 5 import com.chinasoft.dbhelper.SqliteDBHelper; 6 7 public class DiaryDao { 8 9 private SqliteDBHelper sqliteDBHelper; 10 private SQLiteDatabase db; 11 12 // 重寫構造方法 13 public DiaryDao(Context context) { 14 this.sqliteDBHelper = new SqliteDBHelper(context); 15 db = sqliteDBHelper.getWritableDatabase(); 16 } 17 18 // 讀操做 19 public String execQuery(final String strSQL) { 20 try { 21 System.out.println("strSQL>" + strSQL); 22 // Cursor至關於JDBC中的ResultSet 23 Cursor cursor = db.rawQuery(strSQL, null); 24 // 始終讓cursor指向數據庫表的第1行記錄 25 cursor.moveToFirst(); 26 // 定義一個StringBuffer的對象,用於動態拼接字符串 27 StringBuffer sb = new StringBuffer(); 28 // 循環遊標,若是不是最後一項記錄 29 while (!cursor.isAfterLast()) { 30 sb.append(cursor.getInt(0) + "/" + cursor.getString(1) + "/" 31 + cursor.getString(2) + "/" + cursor.getString(3) + "/" 32 + cursor.getString(4)+"#"); 33 //cursor遊標移動 34 cursor.moveToNext(); 35 } 36 db.close(); 37 return sb.deleteCharAt(sb.length()-1).toString(); 38 } catch (RuntimeException e) { 39 e.printStackTrace(); 40 return null; 41 } 42 43 } 44 45 // 寫操做 46 public boolean execOther(final String strSQL) { 47 db.beginTransaction(); //開始事務 48 try { 49 System.out.println("strSQL" + strSQL); 50 db.execSQL(strSQL); 51 db.setTransactionSuccessful(); //設置事務成功完成 52 db.close(); 53 return true; 54 } catch (RuntimeException e) { 55 e.printStackTrace(); 56 return false; 57 }finally { 58 db.endTransaction(); //結束事務 59 } 60 61 } 62 }
咱們在Dao構造方法中實例化sqliteDBHelper並獲取一個SQLiteDatabase對象,做爲整個應用的數據庫實例;在增刪改信息時,咱們採用了事務處理,確保數據完整性;最後要注意釋放數據庫資源db.close(),這一個步驟在咱們整個應用關閉時執行,這個環節容易被忘記,因此朋友們要注意。
咱們獲取數據庫實例時使用了getWritableDatabase()方法,也許朋友們會有疑問,在getWritableDatabase()和getReadableDatabase()中,你爲何選擇前者做爲整個應用的數據庫實例呢?在這裏我想和你們着重分析一下這一點。
咱們來看一下SQLiteOpenHelper中的getReadableDatabase()方法:
1 public synchronized SQLiteDatabase getReadableDatabase() { 2 if (mDatabase != null && mDatabase.isOpen()) { 3 // 若是發現mDatabase不爲空而且已經打開則直接返回 4 return mDatabase; 5 } 6 7 if (mIsInitializing) { 8 // 若是正在初始化則拋出異常 9 throw new IllegalStateException("getReadableDatabase called recursively"); 10 } 11 12 // 開始實例化數據庫mDatabase 13 14 try { 15 // 注意這裏是調用了getWritableDatabase()方法 16 return getWritableDatabase(); 17 } catch (SQLiteException e) { 18 if (mName == null) 19 throw e; // Can't open a temp database read-only! 20 Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e); 21 } 22 23 // 若是沒法以可讀寫模式打開數據庫 則以只讀方式打開 24 25 SQLiteDatabase db = null; 26 try { 27 mIsInitializing = true; 28 String path = mContext.getDatabasePath(mName).getPath();// 獲取數據庫路徑 29 // 以只讀方式打開數據庫 30 db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY); 31 if (db.getVersion() != mNewVersion) { 32 throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to " 33 + mNewVersion + ": " + path); 34 } 35 36 onOpen(db); 37 Log.w(TAG, "Opened " + mName + " in read-only mode"); 38 mDatabase = db;// 爲mDatabase指定新打開的數據庫 39 return mDatabase;// 返回打開的數據庫 40 } finally { 41 mIsInitializing = false; 42 if (db != null && db != mDatabase) 43 db.close(); 44 } 45 }
在getReadableDatabase()方法中,首先判斷是否已存在數據庫實例而且是打開狀態,若是是,則直接返回該實例,不然試圖獲取一個可讀寫模式的數據庫實例,若是遇到磁盤空間已滿等狀況獲取失敗的話,再以只讀模式打開數據庫,獲取數據庫實例並返回,而後爲mDatabase賦值爲最新打開的數據庫實例。既然有可能調用到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 { // 打開或建立數據庫 db = mContext.openOrCreateDatabase(mName, 0, mFactory); } // 獲取數據庫版本(若是剛建立的數據庫,版本爲0) int version = db.getVersion(); // 比較版本(咱們代碼中的版本mNewVersion爲1) if (version != mNewVersion) { db.beginTransaction();// 開始事務 try { if (version == 0) { // 執行咱們的onCreate方法 onCreate(db); } else { // 若是咱們應用升級了mNewVersion爲2,而原版本爲1則執行onUpgrade方法 onUpgrade(db, version, mNewVersion); } db.setVersion(mNewVersion);// 設置最新版本 db.setTransactionSuccessful();// 設置事務成功 } finally { db.endTransaction();// 結束事務 } } onOpen(db); success = true; return db;// 返回可讀寫模式的數據庫實例 } finally { mIsInitializing = false; if (success) { // 打開成功 if (mDatabase != null) { // 若是mDatabase有值則先關閉 try { mDatabase.close(); } catch (Exception e) { } mDatabase.unlock();// 解鎖 } mDatabase = db;// 賦值給mDatabase } else { // 打開失敗的狀況:解鎖、關閉 if (mDatabase != null) mDatabase.unlock(); if (db != null) db.close(); } } }
你們能夠看到,幾個關鍵步驟是,首先判斷mDatabase若是不爲空已打開並非只讀模式則直接返回,不然若是mDatabase不爲空則加鎖,而後開始打開或建立數據庫,比較版本,根據版本號來調用相應的方法,爲數據庫設置新版本號,最後釋放舊的不爲空的mDatabase並解鎖,把新打開的數據庫實例賦予mDatabase,並返回最新實例。
看完上面的過程以後,你們或許就清楚了許多,若是不是在遇到磁盤空間已滿等狀況,getReadableDatabase()通常都會返回和getWritableDatabase()同樣的數據庫實例,因此咱們在DBManager構造方法中使用getWritableDatabase()獲取整個應用所使用的數據庫實例是可行的。固然若是你真的擔憂這種狀況會發生,那麼你能夠先用getWritableDatabase()獲取數據實例,若是遇到異常,再試圖用getReadableDatabase()獲取實例,固然這個時候你獲取的實例只能讀不能寫了
最後,讓咱們看一下如何使用這些數據操做方法來顯示數據,界面核心邏輯代碼:
public class SQLiteActivity extends Activity { public DiaryDao diaryDao; //由於getWritableDatabase內部調用了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()); // 動態組件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() { // 建立數據庫對象 SqliteDBHelper sqliteDBHelper = new SqliteDBHelper(SQLiteActivity.this); sqliteDBHelper.getWritableDatabase(); System.out.println("數據庫建立成功"); } }
Android sqlite3數據庫管理工具
Android SDK的tools目錄下提供了一個sqlite3.exe工具,這是一個簡單的sqlite數據庫管理工具。開發者能夠方便的使用其對sqlite數據庫進行命令行的操做。
程序運行生成的*.db文件通常位於"/data/data/項目名(包括所處包名)/databases/*.db",所以要對數據庫文件進行操做須要先找到數據庫文件:
一、進入shell 命令
adb shell
二、找到數據庫文件
#cd data/data
#ls --列出全部項目
#cd project_name --進入所需項目名
#cd databases
#ls --列出現寸的數據庫文件
三、進入數據庫
#sqlite3 test_db --進入所需數據庫
會出現相似以下字樣:
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
至此,可對數據庫進行sql操做。
四、sqlite經常使用命令
>.databases --產看當前數據庫
>.tables --查看當前數據庫中的表
>.help --sqlite3幫助
>.schema --各個表的生成語句
參考連接: