Android中數據存儲之一------SharedPreferences



       SharedPreferences是android.content包中的一個接口,提供來訪問和修改偏好數據。其處理的是KEY-VALUES類型的數據。其數據存儲位置在/data/data/shared-pref文件夾中,文件的保存格式是.xml格式,導出該文件發現其中確實是以鍵值對的方式存儲的。

       SharedPreferences可以存儲的數據類型有:

       1   簡單類型,如string ,int

       2   複雜的數據類型(對象、圖像),必須經過編碼處理,然後將編碼後的數據以字符串的形式存儲。

       雖然可以用其保存複雜數據類型,但推薦當要存取更多的數據時,採用文件或SQLite.

       sharedPreferences 對數據的操作主要通過它的一個內部接口Editor來完成。Editor提供了對各種數據類型的寫操作,以簽名putXX(,)形式。注意不管是寫入還是移除數據,最後都要調用Editor.commit()方法,進行提交。

      下面看看具體實現:

Activity的代碼:

package com.luise.datastorage;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener,
  OnCheckedChangeListener {

 // 聲明控件變量
 private EditText mUserName;
 private EditText mUserPassword;
 private CheckBox mSaveUser;
 private Button mBtnLogin;
 private String mStrUserName, mStrUserPassword;
 private SharedPreferences msharePreferences;

 private final static String USERNAME = "userName";
 private final static String PASSWORD = "userPassword";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              mUserName = (EditText) findViewById(R.id.et_userName);
              mUserPassword = (EditText) findViewById(R.id.et_userPassword);
              mSaveUser = (CheckBox) findViewById(R.id.cb_saveUser);
              mBtnLogin = (Button) findViewById(R.id.btn_login);

              mBtnLogin.setOnClickListener(this);
              mSaveUser.setOnCheckedChangeListener(this);

 }

 @Override
 public void onCheckedChanged(CompoundButton cbtn, boolean isChecked) {

               mStrUserName = mUserName.getText().toString().trim();
               mStrUserPassword = mUserPassword.getText().toString().trim();

               Editor editor = null; // 得到sharedPerferences對象

              msharePreferences =getSharedPreferences("user", MODE_PRIVATE);
              editor = msharePreferences.edit();

              if (isChecked) {

                        editor.putString(USERNAME, mStrUserName);
                        editor.putString(PASSWORD, mStrUserPassword);

                        editor.commit();
             } else {
             editor.remove(USERNAME);
             editor.remove(PASSWORD);

             editor.commit();
           }

 }

 @Override
 public void onClick(View v) {
          switch (v.getId()) {
         case R.id.btn_login:
                 mStrUserName = mUserName.getText().toString().trim();
                 mStrUserPassword = mUserPassword.getText().toString().trim();

                 if (mStrUserName.equals("ly")
                 && mStrUserPassword.equals("12345")) {
                 Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show();

                } else {
                Toast.makeText(this, "用戶名或密碼錯誤", Toast.LENGTH_SHORT).show();
                }
                break;

          }

 }

 @Override
 protected void onResume() {
              super.onResume();

             msharePreferences = getSharedPreferences("user", MODE_PRIVATE);
             String strUserName = msharePreferences.getString(USERNAME, null);
             String strUserPassword = msharePreferences.getString(PASSWORD, null);

              

            if (strUserName == null || strUserPassword == null) {
                      mSaveUser.setChecked(false);
             } else if (strUserName.equals("liyong") && strUserPassword.equals("12345") ) {
                      mUserName.setText(strUserName);
                      mUserPassword.setText(strUserPassword);
                      mSaveUser.setChecked(true);

         Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show();

           } else {
           Toast.makeText(this, "用戶名或密碼錯誤", Toast.LENGTH_SHORT).show();
           }

       }

}


佈局文件:


<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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="用戶名:" />

    <EditText
        android:id="@+id/et_userName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="密碼:" />

    <EditText
        android:id="@+id/et_userPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" />

    <CheckBox
        android:id="@+id/cb_saveUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="記住用戶名和密碼" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登錄" />

</LinearLayout>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章