【 Android官方文檔讀書筆記】儲存資料

來源:互聯網
上載者:User

標籤: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官方文檔讀書筆記】儲存資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.