像預設歡迎語,登入的使用者名稱和密碼等儲存資訊量小時,可以以索引值對的方式儲存,即SharedPreference儲存,使得我們很方便的存入和讀取
:
當按返回鍵後,再次啟動後,上一次輸入的姓名和密碼仍顯示
布局代碼:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:text="@string/name" /> <EditText android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:text="@string/password" /> <EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:password="true" /></LinearLayout>
MainActivity.java代碼
package cn.bzu.sharedpreference;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.util.Log;import android.view.Menu;import android.widget.EditText;public class MainActivity extends Activity {public static final String SETTING_INFOS="SETTING_Infos";public static final String TAG="MainActivity";private EditText nameText;// 接受使用者名稱組件private EditText passwordText;// 接受密碼組件@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//一旦檔案存在,第2個參數是沒有意義的nameText = (EditText) this.findViewById(R.id.name);passwordText = (EditText) this.findViewById(R.id.password);Log.i(TAG,"onCreate()");SharedPreferences sharedPreferences=getSharedPreferences(SETTING_INFOS, MODE_PRIVATE);String name = sharedPreferences.getString("name", "");//預設值為空白String password = sharedPreferences.getString("password","");if(name!=null&&!"".equals(name)){nameText.setText(name);}if(password!=null&&!"".equals(password)){passwordText.setText(password);}}@Overrideprotected void onStop() {super.onStop();Log.i(TAG,"onStop()");String name = nameText.getText().toString();String password = passwordText.getText().toString();// 第1個參數指定儲存參數的XML檔案的名稱,不需要加尾碼// 第2個參數指定操作模式,只能被本應用所訪問SharedPreferences sharedPreferences=getSharedPreferences(SETTING_INFOS, Context.MODE_PRIVATE);Editor editor=sharedPreferences.edit();editor.putString("name", name);editor.putString("password", password);//此時資料儲存在記憶體中editor.commit();//永久的儲存到xml檔案中,減少頻繁的檔案操作,提高效能。}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.activity_main, menu);return true;}}