Android儲存之SharedPreferences,sharedpreferences
SharedPreferences是Android提供用來儲存一些簡單的配置資訊的一種機制,例如,一些預設歡迎語、登入的使用者名稱和密碼等。其以鍵值對的方式儲存,使得我們可以很方便的讀取和存入,下面看一個示範的例子。
執行個體:SharedPreferencesDemo
代碼邏輯:
應用啟動時嘗試從SharedPreferences中讀取儲存的使用者名稱和使用者密碼,並將結果顯示在UI介面相應的編輯框中。
單擊登入按鈕,如果使用者名稱和使用者密碼編輯框不為空白,則將編輯框中輸入的使用者名稱和密碼儲存到SharedPreferences中,否則提示輸入使用者名稱或密碼。
單擊取消按鈕,清空SharedPreferences,編輯框也設為空白。
運行效果:
初始狀態下兩個編輯框都是空的
第一次啟動 輸入使用者名稱和密碼並單擊登入按鈕
退出應用並重新啟動應用,可以看到前面輸入的使用者名稱和密碼
代碼清單:
布局檔案:activity_main.xml
<?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1" > <TableRow> <TextView android:gravity="right" android:textStyle="bold" android:padding="3dip" android:text="使用者名稱稱:" /> <EditText android:id="@+id/username" android:inputType="text" android:padding="3dip" android:scrollHorizontally="true" /> </TableRow> <TableRow> <TextView android:gravity="right" android:textStyle="bold" android:padding="3dip" android:text="使用者密碼:" /> <EditText android:id="@+id/password" android:inputType="textPassword" android:padding="3dip" /> </TableRow> <TableRow android:gravity="right"> <Button android:id="@+id/cancel" android:text="取消" /> <Button android:id="@+id/login" android:text="登入" /> </TableRow></TableLayout>
Java原始碼檔案:MainActivity.java
package com.rainsong.sharedpreferencesdemo;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity { private static final String PREFERENCES_NAME = "sharedpreferencesdemo"; private static final String KEY_USERNAME = "username"; private static final String KEY_PASSWORD = "password"; Button btn_login; Button btn_cancel; EditText et_username; EditText et_password; OnClickListener listener_login; OnClickListener listener_cancel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_username = (EditText) findViewById(R.id.username); et_password = (EditText) findViewById(R.id.password); listener_login = new OnClickListener() { public void onClick(View v) { String username; String password; username = et_username.getText().toString(); if (username.length() < 1) { Toast.makeText(MainActivity.this, "請輸入使用者名稱", Toast.LENGTH_LONG).show(); return; } password = et_password.getText().toString(); if (password.length() < 1) { Toast.makeText(MainActivity.this, "請輸入密碼", Toast.LENGTH_LONG).show(); return; } SharedPreferences pref = getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND); Editor edit = pref.edit(); edit.putString(KEY_USERNAME, username); edit.putString(KEY_PASSWORD, password); edit.commit(); Toast.makeText(MainActivity.this, "使用者名稱稱:" + username + ", 使用者密碼:" + password,Toast.LENGTH_SHORT).show(); } }; btn_login = (Button)findViewById(R.id.login); btn_login.setOnClickListener(listener_login); listener_cancel = new OnClickListener() { public void onClick(View v) { SharedPreferences pref = getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND); Editor edit = pref.edit(); edit.clear(); edit.commit(); et_username.setText(""); et_password.setText(""); } }; btn_cancel = (Button)findViewById(R.id.cancel); btn_cancel.setOnClickListener(listener_cancel); SharedPreferences pref = getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND); String username; String password; username = pref.getString(KEY_USERNAME, ""); password = pref.getString(KEY_PASSWORD, ""); et_username.setText(username); et_password.setText(password); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }}
通過上述代碼可以看到,在onCreate中使用findViewById得到兩個EditText後,使用getSharedPreferences()方法取得SharedPreferences對象,然後使用getString()方法取得其中儲存的值,最後使用setText()方法將其值設定為兩個EditText的值。
在單擊“登入”按鈕時,首先使用getSharedPreferences()方法取得SharedPreferences對象;然後調用edit()方法使其處於可編輯狀態,並使用putString()方法將兩個EditText中的值儲存起來;最後使用commit()方法提交即可儲存。
API知識點
public abstract class
Context
extends Object
abstract SharedPreferences
getSharedPreferences(String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values.
public interface
SharedPreferences
Class Overview
Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.
abstract SharedPreferences.Editor
edit()
Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
abstract String
getString(String key, String defValue)
Retrieve a String value from the preferences.
public static interface
SharedPreferences.Editor
Class Overview
Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
abstract SharedPreferences.Editor
clear()
Mark in the editor to remove all values from the preferences.
abstract boolean
commit()
Commit your preferences changes back from this Editor to the SharedPreferences object it is editing.
abstract SharedPreferences.Editor
putString(String key, String value)
Set a String value in the preferences editor, to be written back once commit() or apply() are called.