1. 程式人生 > >SharedPreferences實現記住密碼的登入介面-Android

SharedPreferences實現記住密碼的登入介面-Android

 

最近在學習Android的資料儲存,便將自己的理解寫下來。新手淺顯望理解。


在Android中,儲存資料主要採用了3種方案,分別為檔案儲存, SharedPreferences儲存以及資料庫儲存,當然,資料也可以儲存在sd卡里,但相比上面這幾種,可能就要麻煩點了,而且安全性也會降低。

好了,我們今天就來使用它們當中的 SharedPreferences來實現一下簡單的記住密碼功能。


不同於檔案的儲存方式,SharedPreferences是使用鍵值對的方式來儲存資料的。也就是說,當儲存一條資料的時候,需要給這條資料提供一個對應的,這樣在讀取資料的時候就可以通過這個鍵把相應的值取出來。而且 SharePreferences還支援多種不同的資料型別儲存,如果儲存的資料型別是整型,那麼取出來的依然是整型。

 

將資料儲存到 SharedPreferences 中

首先需要獲取到SharedPreferences 物件,Android中主要提供了3種方法用於得到 SharedPreferences 的物件。

1.Context 類中的 getSharedPreferernces() 方法:

含有兩個引數

第一個引數用於指定 SharedPreferences 檔案的名稱,如果指定的檔案不存在,則會建立一個。

第二個引數用於指定操作模式,目前只有 MODE_PRIVATE 這一種模式可選,它是預設目錄下的,和直接傳入0效果是相同的,表示只有當前的應用程度才可以對這個 SharedPreferences 檔案進行讀寫。其他幾種操作模式均已被廢棄。

 

2.Activity類的getPreferences方法

 

 這個方法和Context中的 getSharedPrefereces() 方法很相似,不過它只接受一個操作模式引數,因為使用這個方法會自動將當前活動得類名作為 SharePreferences 的檔名。

 

3.PreferenceManger類中的getDfaultSharedPrefereces()方法

這是一個靜態方法,他接受一個 Context 引數,並自動使用當前應用程式的包名作為字首來命名 SharedPreferences 檔案,得到了 SharedPreferences 物件之後,就可以向 Shared-Preferences 檔案儲存資料了,具體分為3步:

  -1.呼叫 SharePreferences 物件的 edit() 方法來獲取一個 SharedPreferences.Editor 物件。

  -2.向 SharePreferences.Editor 物件中新增資料,比如新增一個布林型資料就使用 putBoolean() 方法,新增一個字串則使用putString()方法,以此類推。

  -3.呼叫 apply() 方法將新增的資料提交,從而完成資料儲存操作。


從 SharedPreferences 中讀取資料

SharedPreferences 提供了一系列的get方法來讀取資料,每個get方法都對應了SharedPreferences.Editor 中的一種put方法,比如讀取一個布林型資料就使用 getBoolean() 方法,讀取一個整型就使用 getInt() 方法,這些get 方法都接收兩個引數,第一個引數是鍵,傳入資料時使用的鍵就可以得到對應的值了,第二個引數是預設值,即表示當傳入的鍵找不到對應的值時會以什麼樣的預設值返回。


 

複習完了基礎,下面就通過一個 記住密碼 的功能來學習一下SharedPreferences

 

首先,開啟as,新建一個專案,修改xml的程式碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:layout_marginLeft="60dp"
        android:text="Login"/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="賬號:"
            android:textSize="30sp"/>
        <EditText
            android:id="@+id/admin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="admin"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密碼:"
            android:textSize="30sp"/>
        <EditText
            android:id="@+id/pass_word"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="password"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:id="@+id/check_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="記住密碼"/>
    </LinearLayout>
    <Button
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="go"/>
</LinearLayout>

不難看出,這裡使用3個線性佈局做了一個簡易的登入介面,如下圖

 

接下來修改MainActivity中的程式碼:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button login;
    private EditText admin,pasd;
    private SharedPreferences pref;
    private CheckBox checkBox;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        login=(Button) findViewById(R.id.login);
        admin=(EditText)findViewById(R.id.admin);
        pasd=(EditText) findViewById(R.id.pass_word);
        pref= PreferenceManager.getDefaultSharedPreferences(this);
        checkBox=(CheckBox) findViewById(R.id.check_box);
        login.setOnClickListener(this);
        boolean isRemember=pref.getBoolean("remember_password",false);      //預設值
        if(isRemember){
                        //將賬號和密碼儲存到文字框內
            String account=pref.getString("account","");
            String password=pref.getString("password","");
            admin.setText(account);
            pasd.setText(password);
            checkBox.setChecked(true);      //勾選記住密碼按鈕
            Toast.makeText(this, "資訊還原成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        String account=admin.getText().toString();      //獲取輸入框的資料
        String password=pasd.getText().toString();
        if(account.equals("admin")&&password.equals("password")){
            editor=pref.edit();
            if(checkBox.isChecked()){       //檢查框中是否被選中
                editor.putBoolean("remember_password",true);
                editor.putString("account",account);
                editor.putString("password",password);
            }else{
                editor.clear();         //清除儲存的資訊
            }
            editor.apply();             //提交資料
        }
        Toast.makeText(this, "登陸成功", Toast.LENGTH_SHORT).show();
    }
}

現在簡單來說一下里面的功能。

首先在onCreate()方法中獲取到了 SharedPreferences 物件,然後呼叫他的 getBoolean() 方法獲取  remember_password 的鍵值。一開始肯定不存在鍵值,所以會使用預設的 false,這樣就什麼都不會發生。這樣在登入成功後,呼叫 ChearBox 的 isChecked() 方法來檢查複選框是否被選中,如果被選中了,則表示使用者想要記住密碼,這時將 remember_password 設定為true,然後把 account和 password對應的值都存到 SharedPreferences檔案中並提交。如果沒有被選中,就簡單呼叫一下 clear()方法,將 SharedPreferences 檔案中的資料全部清除掉。

因為當用戶選中了記住密碼複選框,併成功登陸了一次後,remember_password 鍵對應的值就是 true 了,這時候如果重啟進入登陸介面,就會從 SharedPreferences 將儲存的賬號和密碼讀取出來,並填充到文字框中,然後把記住密碼複選框選中,這樣就完成了記住密碼的功能。這裡我們順便加了兩個Toast用來提示密碼還原和登入成功的提示,雖然沒有登入後的介面,哈哈

下面,我們來看看效果吧-.-

好啦,我會不斷更新的,記錄學習Android的點點滴滴,歡迎和我一起交流。雖然我很菜-.-