Android數據存儲之SharedPreferences使用

SharedPreferences是Android中一種輕型的數據存儲類。本質上是基於XML文件進行存儲Key-Value鍵值對的數據,生成的XML文件的目錄在/data/data/包名/Shared_Pref/下。主要是用來存儲一些簡單的配置信息,如登陸時是否保存用戶名密碼等。html

SharedPreferences自己只能獲取數據而不支持存儲或修改,存儲修改是經過SharedPreferences的一個內部接口Editor來實現的。java

實現SharedPreferences存儲的步驟以下:android

① 獲取SharedPreferences對象;數據庫

② 獲取SharedPreferences.Editor對象;ide

③ 經過Editor接口的putXxx方法保存K-V鍵值對。Xxx表示不一樣的數據類型(float,int,String,boolean,long);佈局

④ 使用Editor接口的commit方法進行操做的提交。this

使用SharedPreferences的過程比較簡單,下面經過一個保存用戶名的小案例演示一下SharedPreferences的簡單使用。url

主佈局文件:spa

<?xml version="1.0" encoding="utf-8"?>
<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">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tvUsername"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="14dp"
            android:text="用戶名"
            android:textSize="20dp"
            android:textAlignment="center"/>
        <EditText
            android:id="@+id/etUsername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/Base.V7.Widget.AppCompat.EditText"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <TextView
            android:id="@+id/tvPassword"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="14dp"
            android:text="密    碼"
            android:textSize="20dp"
            android:textAlignment="center"/>
        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:theme="@style/Base.V7.Widget.AppCompat.EditText"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <TextView
            android:id="@+id/tvRememberUsername"
            android:text="保存用戶名"
            android:textSize="15dp"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
       <CheckBox
           android:id="@+id/cbRememberUsername"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />

    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <Button
            android:id="@+id/btnLogin"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="10dp"
            android:layout_height="60dp"
            android:text="登陸"
            android:textSize="20dp"/>

        <Button
            android:id="@+id/btnCancel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="5dp"
            android:layout_height="60dp"
            android:text="取消"
            android:textSize="20dp"/>

    </LinearLayout>
</LinearLayout>
activity_main

MainActivity.javacode

public class MainActivity extends AppCompatActivity implements View.OnClickListener { //聲明控件
    private EditText etUsername, etPassword; private TextView tvUsername, tvPassword, tvSaveUsername; private CheckBox cbSaveUsername; private Button btLogin, btCancel; //聲明SharedPreferences對象
    private SharedPreferences preferences; //聲明Editor對象
    private SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews();//初始化控件
        /** * 經過getSharedPreferences方法獲取SharedPreferences對象, * getSharedPreferences(String name,int mode) * name: 生成的XML文件的名字 * mode: 生成的XML文件的權限(是否能被其餘程序讀取等) * * 也能夠使用PreferenceManager.getDefaultSharedPreferences(this)獲取SharedPreferences對象, * 這樣生成的XML文件名爲: 包名+「_preferences」 * XML權限爲:MODE_PRIVATE */
// preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preferences = getSharedPreferences("myPref", MODE_PRIVATE); //獲取Editor對象
        editor = preferences.edit(); //經過SharedPreferences對象的getXxx方法獲取Key對應的Value,第二個參數爲默認值
        String name = preferences.getString("username", ""); //若是name爲空,說明還未進行過用戶名的存儲
        if (name == null) { cbSaveUsername.setChecked(false); } else {//若是不爲空則將已存儲的用戶名自動填寫到編輯框中
            cbSaveUsername.setChecked(true); etUsername.setText(name); } } //初始化控件
    private void initViews() { etUsername = (EditText) findViewById(R.id.etUsername); etPassword = (EditText) findViewById(R.id.etPassword); tvUsername = (TextView) findViewById(R.id.tvUsername); tvPassword = (TextView) findViewById(R.id.tvPassword); tvSaveUsername = (TextView) findViewById(R.id.tvRememberUsername); cbSaveUsername = (CheckBox) findViewById(R.id.cbRememberUsername); btLogin = (Button) findViewById(R.id.btnLogin); btCancel = (Button) findViewById(R.id.btnCancel); btLogin.setOnClickListener(this); btCancel.setOnClickListener(this); } //按鈕點擊事件
 @Override public void onClick(View v) { //獲取到編輯框中的用戶名和密碼
        String name = etUsername.getText().toString(); String pass = etPassword.getText().toString(); switch (v.getId()) { //登陸按鈕的點擊處理
            case R.id.btnLogin: //若是用戶名和密碼合法
                if ("admin".equals(name) && "abc123".equals(pass)) { //若是勾選了保存用戶名的複選框,則將用戶名存儲到XML文件中
                    if (cbSaveUsername.isChecked()) { editor.putString("username", name); } else {//若是沒有勾選則將用戶名從XML文件中移除(若是有的話)
                        editor.remove("username"); } //使用Editor對象操做後,須要調用commit方法進行提交,否則全部的操做都無效。相似與數據庫中事務的提交
 editor.commit(); Toast.makeText(this, "登陸成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "登陸失敗", Toast.LENGTH_SHORT).show(); } break; case R.id.btnCancel: break; } } }

完整源碼 :  點擊下載

 

做者: caobotao
本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文連接,不然保留追究法律責任的權利。
相關文章
相關標籤/搜索