在Android系統中提供了多種存儲技術.通過這些存儲技術可以將數據存儲在各種存儲介質上.比如sharedpreferences可以將數據保存着應用軟件的私有存儲區,這些存儲區的數據只能被寫入這些數據的軟件讀取.當然Android還支持文件存儲、SQLite數據庫和Content Provider。在這里我們將對sharedpreferences存儲方式進行介紹。
SharedPreferences是一種輕量級的數據存儲方式,學過Web開發的同學,可以想象它是一個小小的Cookie。它可以用鍵值對的方式把簡單數據類型(boolean、int、float、long和String)存儲在應用程序的私有目錄下(data/data/包名 /shared_prefs/)自己定義的xml文件中。
SharedPreferences是以鍵值對來存儲應用程序的配置信息的一種方式,它只能存儲基本數據類型。一個程序的配置文件僅可以在本應用程序中使用,或者說只能在同一個包內使用,不能在不同的包之間使用。實際上sharedPreferences是采用了XML格式將數據存儲到設備中,在DDMS中的File Explorer中的/data/data//shares_prefs下。
一、獲取SharedPreferences對象的方法
(1)通過函數Context.getSharedPreferences(String name,int mode),其中name為本組件的配置文件名(如果想要與本應用程序的其他組件共享此配置文件,可以用這個名字來檢索到這個配置文件),mode為操作模式,默認的模式為0或MODE_PRIVATE;返回值為SharedPreferences。
(2)通過函數Activity.getPreferences(int mode),其中配置文件僅可以被調用的Activity使用。mode為操作模式,默認的模式為0或MODE_PRIVATE;返回值為SharedPreferences。
二、使用SharedPreferences存取數據
保存key-value對一般要指定一個文件名,然后用類似putString的方法指定key和value。SharedPreferences也采用了同樣的方法。使用SharedPreferences保存key-value對的步驟如下:
(1) 使用Activity類的getSharedPreferences方法獲得SharedPreferences對象。其中存儲key-value的文件名的名稱由getSharedPreferences方法的第一個參數指定。
(2) 使用SharedPreferences接口的edit獲得SharedPreferences.Editor對象。
(3) 通過SharedPreferences.Editor接口的putXXX方法保存key-value對。其中XXX表示value的不同數據類型。Boolean類型的value則是用putBoolean方法,字符串類型的則為putString方法。
(4) 通過SharedPreferences.Editor接口的commit方法保存key-value對。Commit方法相當於數據庫事務中的提交(commit)操作。只有在事件結束后進行提交,才會將數據真正保存在數據庫中。保存key-value也是一樣。
三、數據的存儲位置和格式
SharedPreferences將數據文件寫在手機內存私有的目錄中。在模擬器中測試程序可以通過ADT的DDMS透視圖來查看數據文件的位置。
四、保存較為復雜的類型的數據
前面介紹的SharedPreferences只能保存簡單類型的數據,例如,string,int等。如果需要存取比較復雜的數據類型比如類或者圖像,則需要對這些數據進行編碼,通常將其轉換成Base64編碼,然后將轉換后的數據以字符串的形式保存在XML文件中。
SharedPreferences保存List集合

public static String WeatherList2String(List<Weather> WeatherList) throws IOException { // 實例化一個ByteArrayOutputStream對象,用來裝載壓縮后的字節文件。 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 然后將得到的字符數據裝載到ObjectOutputStream ObjectOutputStream objectOutputStream = new ObjectOutputStream( byteArrayOutputStream); // writeObject 方法負責寫入特定類的對象的狀態,以便相應的 readObject 方法可以還原它 objectOutputStream.writeObject(WeatherList); // 最后,用Base64.encode將字節文件轉換成Base64編碼保存在String中 String WeatherListString = new String(Base64.encode( byteArrayOutputStream.toByteArray(), Base64.DEFAULT)); // 關閉objectOutputStream objectOutputStream.close(); return WeatherListString; } @SuppressWarnings("unchecked") public static List<Weather> String2WeatherList(String WeatherListString) throws StreamCorruptedException, IOException, ClassNotFoundException { byte[] mobileBytes = Base64.decode(WeatherListString.getBytes(), Base64.DEFAULT); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( mobileBytes); ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream); List<Weather> WeatherList = (List<Weather>) objectInputStream .readObject(); objectInputStream.close(); return WeatherList; }
SharedPreferences保存圖片和可序列化的對象

查看源代碼 package android.test.sharedpreferencescomplex; import java.io.Serializable; public class MobileInfo implements Serializable { private static final long serialVersionUID = 1L; public String name; public String infoString; } package android.test.sharedpreferencescomplex; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import android.os.Bundle; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.util.Base64; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onclick_Write_Image(View v) throws Throwable { SharedPreferences sharedPreferences = getSharedPreferences("complex", Activity.MODE_PRIVATE); Editor editor = sharedPreferences.edit(); ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream(); BitmapFactory.decodeResource(getResources(), R.drawable.image1).compress(CompressFormat.JPEG, 50, byteArrayOutputStream); String imageString = new String(Base64.encode(byteArrayOutputStream.toByteArray(),Base64.DEFAULT)); editor.putString("image", imageString); editor.commit(); byteArrayOutputStream.close(); } public void onclick_Read_Image(View view) throws Throwable { SharedPreferences sharedPreferences = getSharedPreferences("complex",Activity.MODE_PRIVATE); String string = sharedPreferences.getString("image", ""); byte[] imageBytes = Base64.decode(string.getBytes(), Base64.DEFAULT); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageBytes); ImageView imageView =(ImageView)findViewById(R.id.imageView1); imageView.setImageDrawable(Drawable.createFromStream(byteArrayInputStream, "image")); byteArrayInputStream.close(); } public void onclick_Write_Data(View view) throws Throwable { MobileInfo mobile = new MobileInfo(); mobile.name = "魅族"; mobile.infoString = "魅族MX"; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(mobile); SharedPreferences sharedPreferences = getSharedPreferences("complex", Activity.MODE_PRIVATE); Editor editor = sharedPreferences.edit(); sharedPreferences = getSharedPreferences("complex",Activity.MODE_PRIVATE); String mobilesString = new String(Base64.encode(byteArrayOutputStream.toByteArray(),Base64.DEFAULT)); editor.putString("mobile", mobilesString); editor.commit(); objectOutputStream.close(); } public void onclick_Read_Data(View view) throws Throwable, Throwable { SharedPreferences sharedPreferences = getSharedPreferences("complex", Activity.MODE_PRIVATE); String mobilesString = sharedPreferences.getString("mobile", ""); byte[] mobileBytes = Base64.decode(mobilesString.getBytes(),Base64.DEFAULT); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(mobileBytes); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); MobileInfo mobileInfo = (MobileInfo) objectInputStream.readObject(); Toast.makeText(this,"手機品牌:" + mobileInfo.name + "\n手機型號:" + mobileInfo.infoString, Toast.LENGTH_LONG).show(); objectInputStream.close(); } }
五、設置數據文件的訪問權限
因為Android系統並不是完全的創新的操作系統,而是在linux內核基礎上發展起來的一個移動操作系統,所以android還有一些linux的基本特性。我們用getsharedPreferences方法獲得sharedpreferences對象,getsharedPreferences方法的第2個參數值使用到了Activity.MODE_PRIVATE常量。除了這個常量以外還可以使用另外3個常量。這4個常量用於指定文件的建立模式。他們一個重要的功能就是設置文件的屬性,從而可以設置數據文件的訪問權限。
六、可以保存設置的Activity:PreferenceActivity
由於SharedPreferences可以很容易的保存key-value對,因此,通常使用SharedPreferences保存配置信息。不過Android SDK提供了更為容易的方法來設計配置界面,並且可以透明地保存配置信息。這就是PreferenceActivity。
PreferenceActivity是Activity的子類,該類封裝了SharedPreferences。因此,PreferenceActivity的所有子類都擁有保存key-value對的能力。
PreferenceActivity提供了一些常用的設置項,這些設置項可以滿足大多數的配置界面的要求。與組件一樣,這些配置項既可以從XML文件創建,也可以從代碼創建。比較常用的有:
- CheckboxPreference:對應標簽。該設置項會創建一個CheckBox組件。
- EditTextPreference:對應標簽。單擊該設置項會彈出一個帶EditText組件的對話框。
- ListPreference:對應標簽。單擊該設置項會彈出帶ListView組件的對話框。
推薦文章:http://www.cnblogs.com/ikarl/archive/2012/11/13/2768344.html