Android:SharedPreference實(shí)例詳解

  • 2016年12月8日,Google中國(guó)開(kāi)發(fā)者大會(huì)在京舉行,同時(shí)正式上線了Google中國(guó)開(kāi)發(fā)者網(wǎng)站Google Developers,查看官方學(xué)習(xí)資源再也不用爬梯子了

在Android系統(tǒng)中,常用的數(shù)據(jù)儲(chǔ)存方式有四種:

  1. 存儲(chǔ)在手機(jī)內(nèi)存中ROM
  2. 存儲(chǔ)在SD卡中
  3. 存儲(chǔ)在SharedPreferences中
  4. 存儲(chǔ)在SQLite數(shù)據(jù)庫(kù)中

在這里只介紹Android特有的SP和SQLite

SharedPreferences

SharedPreferences是Android平臺(tái)上一個(gè)輕量級(jí)的存儲(chǔ)類,主要是保存一些常用的配置,它提供了Android平臺(tái)常規(guī)的Long、Int、String字符串型的保存。

SharedPreferences類似過(guò)去Windows系統(tǒng)上的ini配置文件,但是它分為多種權(quán)限,可以全局共享訪問(wèn),整體效率來(lái)看不是特別的高,對(duì)于常規(guī)的輕量級(jí)而言比SQLite要好不少,如果真的存儲(chǔ)量不大可以考慮自己定義文件格式。

xml 處理時(shí)Dalvik會(huì)通過(guò)自帶底層的本地XML Parser解析,比如XMLpull方式,這樣對(duì)于內(nèi)存資源占用比較好。

這種方式應(yīng)該是用起來(lái)最簡(jiǎn)單的Android讀寫(xiě)外部數(shù)據(jù)的方法了。他以一種簡(jiǎn)單、 透明的方式來(lái)保存一些用戶個(gè)性化設(shè)置的字體、顏色、位置等參數(shù)信息。一般的應(yīng)用程序都會(huì)提供“設(shè)置”或者“首選項(xiàng)”的這樣的界面,那么這些設(shè)置最后就可以通過(guò)Preferences來(lái)保存,而程序員不需要知道它到底以什么形式保存的,保存在了什么地方。當(dāng)然,如果你愿意保存其他的東西,也沒(méi)有什么限制。只是在性能上不知道會(huì)有什么問(wèn)題。
在Android系統(tǒng)中該文件保存在:/data/data/PACKAGE_NAME /shared_prefs 目錄下。

下面是一個(gè)使用SP做數(shù)據(jù)存儲(chǔ)模擬用戶登錄的案例:
布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText 
    android:layout_marginTop="10dp"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:hint="請(qǐng)輸入用戶名"
    android:id="@+id/et_username"
    />
<EditText 
    android:layout_marginTop="10dp"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:hint="請(qǐng)輸入密碼"
    android:inputType="textPassword"
    android:id="@+id/et_pwd"
    />
    <LinearLayout 
    android:layout_marginTop="10dp"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:gravity="right"
    >
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登陸"
        android:onClick="login"
        />
    <CheckBox 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存密碼"
         android:layout_marginRight="10dp"
         android:id="@+id/cb"
        />
</LinearLayout>
</LinearLayout>

案例代碼:

public class MainActivity extends Activity {
private EditText et_username;
private EditText et_pwd;
private CheckBox cb;
//聲明一個(gè)SharedPreferences對(duì)象
private SharedPreferences sp;
/*
 * 為了方便,因此將用戶名和密碼設(shè)置為常量
 */
private static final String PWD = "123456";
private static final String USERNAME = "wzy";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /*
     * 第二個(gè)參數(shù)代表的是創(chuàng)建該文件的訪問(wèn)范圍(權(quán)限),通常并建議選擇MODE_PRIVATE,該值為0,
     * 意思是只有當(dāng)前應(yīng)用可以訪問(wèn)該文件。而還有2個(gè)可選項(xiàng)MODE_WORLD_READABLE 和MODE_WORLD_WRITEABLE
     * 值分別為1和2已經(jīng)廢除,因?yàn)檫@兩種方式可以允許其他應(yīng)用來(lái)訪問(wèn)此文件,這是很不安全的。
     */
    sp = getSharedPreferences("info", MODE_PRIVATE);
    et_username = (EditText) findViewById(R.id.et_username);
    et_pwd = (EditText) findViewById(R.id.et_pwd);
    cb = (CheckBox) findViewById(R.id.cb);
    /*


 * 從sp中獲取用戶信息,用戶數(shù)據(jù)的回顯
     * 第二個(gè)參數(shù)為默認(rèn)返回值,也就是當(dāng)要查找的key-value不存在時(shí),返回的數(shù)據(jù)
     */
    String username = sp.getString("username", "");
    String pwd = sp.getString("pwd", "");
    et_username.setText(username);
    et_pwd.setText(pwd);
}

public void login(View view){
    String userName = et_username.getText().toString();
    String pwd = et_pwd.getText().toString();
    boolean checked = cb.isChecked();
    /*
     * 用戶名和密碼如果為空,則提示用戶。
     */
    if (TextUtils.isEmpty(userName)) {
        Toast.makeText(this, "用戶名不能為空!", Toast.LENGTH_SHORT).show();
        return ;
    }
    if (TextUtils.isEmpty(pwd)) {
        Toast.makeText(this, "密碼不能為空!", Toast.LENGTH_SHORT).show();
        return ;
    }
    /*
     * 如果用戶選擇了保存密碼,則將用戶名和密碼保存在手機(jī)內(nèi)存中
     * 如果沒(méi)有選擇就將文件刪除
     */
if (USERNAME.equals(userName)&&PWD.equals(pwd)) {
        if (checked) {
            /*
             * 在對(duì)sp進(jìn)行寫(xiě)、修改需要獲取Editor對(duì)象
             */
            Editor editor = sp.edit();
            editor.putString("username", userName);
            editor.putString("pwd", pwd);
            /*
             * 此處非常重要,執(zhí)行完修改或者寫(xiě)操作后只有調(diào)用sp的commit方法,數(shù)據(jù)才會(huì)被保存下來(lái)。
             */
            editor.commit();


}else {//刪除用戶文件
            Editor editor = sp.edit();
            /*
             * 刪除該sp中的所有數(shù)據(jù)
             */
            editor.clear();
            editor.commit();
        }
        Toast.makeText(this, "恭喜您,登陸成功!", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this, "對(duì)不起,登陸失??!", Toast.LENGTH_SHORT).show();
    }
}
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,008評(píng)論 25 709
  • 面試題總結(jié) 通用 安卓學(xué)習(xí)途徑, 尋找資料學(xué)習(xí)的博客網(wǎng)站 AndroidStudio使用, 插件使用 安卓和蘋(píng)果的...
    JingBeibei閱讀 1,869評(píng)論 2 21
  • 曾經(jīng)有段時(shí)間喜歡瑜伽,甚至有些走火入魔。那時(shí)候買了張會(huì)員卡,幾乎每星期都會(huì)去練幾次,每?練完人都覺(jué)得非常輕松。 原...
    RainbowPeng閱讀 1,371評(píng)論 14 46
  • 考察團(tuán)合影 【澳門日?qǐng)?bào)消息】由澳門南安同鄉(xiāng)會(huì)、商會(huì)組織的“閩澳一家親 情系海絲源”澳門南安青年福建尋根探源考察團(tuán),...

友情鏈接更多精彩內(nèi)容