標籤:sqlite 資料儲存 share
Android提供了3種資料儲存方式:SharePreference、檔案與資料庫。
1,SharePreference
如果想儲存一個相對較小的key-values集合,可以使用 SharedPreferences API. SharedPreferences對象指向包含key-value對的檔案,並且提供簡單的讀寫方式。每個SharedPreferences檔案均由架構管理,私人或共用均可使用。其本質是一個xml檔案。
資料讀入:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
long highScore = sharedPref.getInt(key, defaultValue);
資料寫入:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
2,檔案
File 對象適用於在start-to-finish讀取或寫入大量資料,File對象適合於讀取或者寫入大量資料,但是缺點是更新資料比較困難。Android檔案儲存體分為內部儲存和外部儲存。內部儲存特點:始終可用;儲存的檔案只能用於預設應用程式;當使用者卸載應用程式時,系統會從內部儲存刪除應用程式所有檔案。因此,當要確保無論使用者還是其他應用程式均可訪問檔案時,內部儲存無疑是最好的選擇。外部儲存的特點:並不總是可用的;具有全域可讀性,所以儲存的檔案可能被控制範圍外的人讀取;使用者想要卸載應用程式,只有當 應用程式檔案儲存在getExternalFilesDir()目錄時系統才會刪除應用程式檔案。因此,對於不需要訪問限制的檔案以及要同其他應用程式共用或者允許使用者使用電腦訪問的檔案,外部儲存無疑是最好的途徑。
在內部儲存儲存檔案時,你可以調用兩種方法之一來擷取相應的目錄檔案:
getFilesDir() 返回表示應用程式內部目錄的檔案
getCacheDir() 返回表示應用程式臨時快取檔案的內部目錄的檔案。
外部儲存的許可權:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
3,資料庫
Android使用SQLite來支援資料庫操作,SQLite是一個輕量級的資料庫,支援基本SQL文法,是常被採用的一種資料存放區方式。Android為此資料庫提供了一個名為SQLiteDatabase的類,封裝了一些操作資料庫的API。一般重複或結構化資料使用資料庫來儲存。
資料讀取樣本:
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don‘t group the rows
null, // don‘t filter by row groups
sortOrder // The sort order
);
更新資料寫庫樣本:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
ContentValues values = new ContentValues();// New value for one column
values.put(FeedEntry.COLUMN_NAME_TITLE, title);// Which row to update, based on the ID
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
int count = db.update(FeedReaderDbHelper.FeedEntry.TABLE_NAME, values, selection, selectionArgs);
【 Android官方文檔讀書筆記】儲存資料