1. 程式人生 > >Android使用SharedPreferences保存賬號密碼

Android使用SharedPreferences保存賬號密碼

思路 才會 clas style 保存密碼 pri bsp mit mat

有很多的應用都會有保存密碼和賬號的功能,比如QQ。接下來就講講使用SharedPreferences來保存密碼和賬號,也許有些人會考慮的數據庫,但是我個人認為對於保存簡單的數據,使用的數據庫就大材小用了,SharedPreferences比較輕量級

首先寫好布局,只有兩個輸入框和一個按鈕

<EditText
        android:id="@+id/number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType
="number" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" /> <Button android:id="@+id/save" android:text="保存" android:layout_width
="match_parent" android:layout_height="wrap_content" />

技術分享

獲取取控件

    private EditText number;
    private EditText password;
    private Button save;

     number = (EditText) findViewById(R.id.number);
     password = (EditText) findViewById(R.id.password);
     save = (Button) findViewById(R.id.save);

在獲取控件之後,還要獲取SharedPreferences,第一參數為保存的文件名,第二個為保存的模型,當文件存在就讀取,如果不存在就創建

private SharedPreferences sp;

//
第一參數為保存的文件名,第二個為保存的模型,當文件存在就讀取,如果不存在就創建 sp = getSharedPreferences("info",MODE_PRIVATE);

增加按鈕點擊事件,點擊按鈕保存賬號和密碼

save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //獲取輸入框的賬號和密碼
                String numberStr = number.getText().toString().trim();
                String passwordStr = password.getText().toString().trim();
                //判斷是否為空
                if (numberStr.isEmpty() || passwordStr.isEmpty()){
                    Toast.makeText(getApplicationContext(),"賬號或密碼不能為空",Toast.LENGTH_SHORT).show();
                }else {
                    //獲取Editor
                    SharedPreferences.Editor editor = sp.edit();
                    //輸入內容
                    editor.putString("number",numberStr);
                    editor.putString("password",passwordStr);
                    //必須提交才會生效,也可以使用apply
                    editor.commit();
                    Toast.makeText(getApplicationContext(),"保存成功",Toast.LENGTH_SHORT).show();
                }
            }
        });

當我們保存賬號和密碼後,想要在第二次打開應用時直接寫密碼和賬號,還有在加載頁面時獲取數據

//獲取info文件的內容,第一參數為保存時的key,第二個是如果獲取不到的默認值
        String numberStr1 = sp.getString("number","");
        String passwordStr2 = sp.getString("password","");
        number.setText(numberStr1);
        password.setText(passwordStr2);

效果圖

技術分享

這個info.xml的文件保存在data/data/包名/shared_prefs/info.xml,可以看到是以XML格式保存的

技術分享

技術分享

最後再來理一理整個思路

保存

①通過getSharedPreferences("文件名",模式)獲得SharedPreferences

②通過sp.edit()獲取Editor

③使用editor調用putXXX(key,value)保存數據

④使用editor調用apply()或者commit()才會生效

讀取

①通過getSharedPreferences("文件名",模式)獲得SharedPreferences

②通過sp.getXXX(key,defValue)直接可以獲得數據

Android使用SharedPreferences保存賬號密碼