Android-SharedPreferences,sharedpreferences
[返回目錄]
SharedPreferences提供一種按“Key=value”的形式進行資料存放區
android.content.SharedPreferences借口所儲存的資訊只能是一些基本的資料類型,如字串,整形,布爾型等
SharedPreferences儲存的是設定檔,檔案尾碼預設為 *.xml,跟Java中的Properties類一樣(只能儲存基本的資料類型)
不能儲存中文,中文需要轉碼
預設情況下,所有設定檔都儲存在系統檔案夾中,/data/data/包名/shared prefs下
Window->show View->Others->File Explorer可以查看系統檔案夾
如:
<span style="font-family:SimHei;font-size:18px;">package com.example.testsharedpreferences;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;public class MainActivity extends Activity {private final String FILENAME="potato"; //儲存檔案名稱,最後產生potato.xml檔案@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);SharedPreferences sharedPreferences=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);SharedPreferences.Editor edit=sharedPreferences.edit();edit.putString("name", "potato");edit.putInt("age", 22);edit.putBoolean("isStudent", true);edit.commit();}}</span>
在系統檔案夾中的/data/data/ com.example.testsharedpreferences/shared prefs下會增加一個 potato.xml檔案
其中,SharedPreferences中儲存資料是通過SharedPreferences.Editor介面進行的
讀取SharedPreferences的資料方法如下:
<span style="font-family:SimHei;font-size:18px;">package com.example.testsharedpreferences;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.util.Log;public class MainActivity extends Activity {private final String FILENAME="potato"; //儲存檔案名稱,最後產生potato.xml檔案@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);SharedPreferences sharedPreferences=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);Log.e("Potato", "Name:"+sharedPreferences.getString("name", "我是預設值"));Log.e("Potato", "Age:"+sharedPreferences.getInt("age", 1));Log.e("Potato", "isStudent:"+sharedPreferences.getBoolean("isStudent", false));}}</span>
對於安卓的sharedpreferences的問題
刪除xml檔案不能徹底刪除SharedPreferences。具體可以看android的源碼,這個東西是靜態,只要沒有被回收,還是能在緩衝中讀出原來的資料。
徹底刪除的辦法是:用editor的clear並且要commit。不能這麼暴力的…………
android SharedPreferences的封裝
這裡我幫你簡單的封裝了一下。blog.csdn.net/...542944 只封裝了string和int類型,其他類型同理。你可以看一下。。。。一定要設滿意答案呀。寫了好一會呢。