(Android review)SharePreferences的使用,androidshare
典型應用場合:
進入某一介面以後,顯示預設值(其實這個也可以通過直接在布局檔案中指定)
基本點:
1)SharePreferences所產生的檔案最終還是以.xml檔案的形式存在於/data/data/應用程式套件名/share_prefs/xxx.xml中
2)SharePreferences適合用於儲存key-value型的資料
基本使用:
存:
Editor editor = sp.edit();//擷取編輯器editor.putString("name", name);//儲存資料(還沒進入進入檔案)editor.putString("phone", phone);editor.putString("email", email);editor.commit();//提交修改(類似於事務)
取:
sp = getSharedPreferences("data", MODE_PRIVATE);//擷取對象,預設指向當前應用.檔案名稱為data.xml,模式為私人// sp = getPreferences(MODE_PRIVATE);//這時候產生的檔案名稱為MainActivity.xmlet_name.setText(sp.getString("name", ""));et_phone.setText(sp.getString("phone", ""));et_email.setText(sp.getString("email", ""));
解析:為什麼我們使用getPreferences(MODE_PRIVATE)時產生的檔案名稱為MainActivity.xml呢??如所示:
其實在之前的部落格我就提過,這種很類似的函數,在底層實現的時候,很可能就是你調我,我調你的。。。事實勝於雄辯,源碼面前無秘密。。現在我們就去看看Android源碼中這兩個函數就知道了。。。
源碼分析:
先看getSharedPreferences(String name, int mode):
@Override public SharedPreferences getSharedPreferences(String name, int mode) { return mBase.getSharedPreferences(name, mode); }
接下來,看一下getPreferences(int mode):
/** * Retrieve a {@link SharedPreferences} object for accessing preferences * that are private to this activity. This simply calls the underlying * {@link #getSharedPreferences(String, int)} method by passing in this activity's * class name as the preferences name. * * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default * operation, {@link #MODE_WORLD_READABLE} and * {@link #MODE_WORLD_WRITEABLE} to control permissions. * * @return Returns the single SharedPreferences instance that can be used * to retrieve and modify the preference values. */ public SharedPreferences getPreferences(int mode) { return getSharedPreferences(getLocalClassName(), mode); }
getPreferences(int mode)方法中用到了getLocalClassName()這個函數,其實這個函數不需要看它的源碼,單單是看它的名字就知道他是幹什麼的了:擷取當前Activity的名字。。。。不過既然看到這裡了,我們還是去看一下它的源碼都是怎麼寫的吧。
/** * Returns class name for this activity with the package prefix removed. * This is the default name used to read and write settings. * * @return The local class name. */ public String getLocalClassName() { final String pkg = getPackageName(); final String cls = mComponent.getClassName();//擷取長類名:包名+類名 int packageLen = pkg.length(); if (!cls.startsWith(pkg) || cls.length() <= packageLen || cls.charAt(packageLen) != '.') { return cls; } return cls.substring(packageLen+1);//截取包名後面的那一段.也就是類名 }
例子:
1、MainActivity
package com.example.sharepreferencetest;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.view.Menu;import android.view.View;import android.widget.EditText;public class MainActivity extends Activity {private EditText et_name;private EditText et_phone;private EditText et_email;private SharedPreferences sp;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main); et_name = (EditText) findViewById(R.id.nameET);et_phone = (EditText) findViewById(R.id.phoneET);et_email = (EditText) findViewById(R.id.emailET);sp = getSharedPreferences("data", MODE_PRIVATE);//擷取對象,預設指向當前應用.檔案名稱為data.xml,模式為私人// sp = getPreferences(MODE_PRIVATE);//這時候產生的檔案名稱為MainActivity.xmlet_name.setText(sp.getString("name", ""));et_phone.setText(sp.getString("phone", ""));et_email.setText(sp.getString("email", ""));}public void onClick(View view){String name = et_name.getText().toString();String phone = et_phone.getText().toString();String email = et_email.getText().toString();Editor editor = sp.edit();//擷取編輯器editor.putString("name", name);//儲存資料(還沒進入進入檔案)editor.putString("phone", phone);editor.putString("email", email);editor.commit();//提交修改(類似於事務)}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
2、main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="姓名" /> <EditText android:id="@+id/nameET" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" > <requestFocus /> </EditText> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="電話" /> <EditText android:id="@+id/phoneET" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="郵箱" /> <EditText android:id="@+id/emailET" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="儲存為預設" /></LinearLayout>
:
產生的data.xml檔案的內容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map><string name="email">1019648568@qq.com</string><string name="phone">13675173829</string><string name="name">hjd</string></map>
源碼下載:http://download.csdn.net/detail/caihongshijie6/7615023
對於android開發的sharePreferences讀取問題
int age=sharePreferences.getInt("Age",20);
這句話的意思是先從sharePreferences裡面找key 為 “Age” 的資料, 如果有,說明你事先儲存過, 那就取“Age”對應的值,也就是你事先儲存過的值 ,如果沒找到key 為“Age” 的,最後的 int age 將被賦予你給的預設值20 ,也就是說那僅僅是一個預設值,只有在從sp對象裡取值失敗的時候才會使用。
插入也就是儲存,也比較簡單:
得到sp 的方法一樣:
SharePreferences sharePreferences = getSharePreferences(PREFERENCE_NAME,MOD);sharePreferences.edit().putInt("Age",28).commit();比上代碼:如果你之前儲存過“Age" 並且儲存的值上28, 那麼 int age=sharePreferences.getInt("Age",20);
這裡age 的值肯定是28 ,而不是20 。
android的sharePreferences怎儲存多個資料
它是以AVP的形式存放的,那就建立多個AVP