Android 資料存放區五種方式

來源:互聯網
上載者:User

標籤:自己   proc   ati   條件查詢   xml檔案   setting   ref   div   ntp   

1、概述

  Android提供了5種方式來讓使用者儲存持久化應用程式資料。根據自己的需求來做選擇,比如資料是否是應用程式私人的,是否能被其他程式訪問,需要多少資料存放區空間等,分別是: 
  
① 使用SharedPreferences儲存資料 

② 檔案儲存體資料

③  SQLite資料庫儲存資料

④ 使用ContentProvider儲存資料

⑤ 網路儲存資料 

Android提供了一種方式來暴露你的資料(甚至是私人資料)給其他應用程式 - ContentProvider。它是一個可選組件,可公開讀寫你應用程式資料。

 

2、SharedPreferences儲存

  SharedPreference類提供了一個總體架構,使您可以儲存和檢索的任何基礎資料型別 (Elementary Data Type)( boolean, float, int, long, string)的持久鍵-值對(基於XML檔案儲存體的“key-value”索引值對資料)。

  通常用來儲存程式的一些配置資訊。其儲存在“data/data/程式包名/shared_prefs目錄下。

  xml 處理時Dalvik會通過內建底層的本地XML Parser解析,比如XMLpull方式,這樣對於記憶體資源佔用比較好。 

2.1  我們可以通過以下兩種方法擷取SharedPreferences對象(通過Context):

① getSharedPreferences (String name, int mode)

   當我們有多個SharedPreferences的時候,根據第一個參數name獲得相應的SharedPreferences對象。

② getPreferences (int mode)

 如果你的Activity中只需要一個SharedPreferences的時候使用。

 

這裡的mode有四個選項:

Context.MODE_PRIVATE

該SharedPreferences資料只能被本應用程式讀、寫。

 

Context.MODE_WORLD_READABLE

該SharedPreferences資料能被其他應用程式讀,但不能寫。

 

Context.MODE_WORLD_WRITEABLE

該SharedPreferences資料能被其他應用程式讀和寫。

 

Context.MODE_MULTI_PROCESS

sdk2.3後添加的選項,當多個進程同時讀寫同一個SharedPreferences時它會檢查檔案是否修改。

 

2.2  向Shared Preferences中寫入值
 
首先要通過 SharedPreferences.Editor擷取到Editor對象;

然後通過Editor的putBoolean() 或 putString()等方法存入值;

最後調用Editor的commit()方法提交;

//Use 0 or MODE_PRIVATE for the default operation SharedPreferences settings = getSharedPreferences("fanrunqi", 0);SharedPreferences.Editor editor = settings.edit();editor.putBoolean("isAmazing", true); // 提交本次編輯editor.commit();

 

同時Edit還有兩個常用的方法:

editor.remove(String key) :下一次commit的時候會移除key對應的索引值對 editor.clear():移除所有索引值對

 

2.3  從Shared Preferences中讀取值

  讀取值使用 SharedPreference對象的getBoolean()或getString()等方法就行了(沒Editor 啥子事)。

SharedPreferences settings = getSharedPreferences("fanrunqi", 0);boolean isAmazing= settings.getBoolean("isAmazing",true);

2.4  Shared Preferences的優缺點

  可以看出來Preferences是很輕量級的應用,使用起來也很方便,簡潔。但儲存資料類型比較單一(只有基礎資料型別 (Elementary Data Type)),無法進行條件查詢,只能在不複雜的儲存需求下使用,比如儲存配置資訊等。

 

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.