Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android存儲之SharedPreferences

Android存儲之SharedPreferences

編輯:關於Android編程

SharedPreferences是Android提供用來存儲一些簡單的配置信息的一種機制,例如,一些默認歡迎語、登錄的用戶名和密碼等。其以鍵值對的方式存儲,使得我們可以很方便的讀取和存入,下面看一個演示的例子。

實例:SharedPreferencesDemo
代碼邏輯:
應用啟動時嘗試從SharedPreferences中讀取保存的用戶名和用戶密碼,並將結果顯示在UI界面相應的編輯框中。
單擊登錄按鈕,如果用戶名和用戶密碼編輯框不為空,則將編輯框中輸入的用戶名和密碼保存到SharedPreferences中,否則提示輸入用戶名或密碼。
單擊取消按鈕,清空SharedPreferences,編輯框也設為空。

運行效果:
初始狀態下兩個編輯框都是空的
\

第一次啟動 輸入用戶名和密碼並單擊登錄按鈕
vceww+bK5MjrtcTTw7unw/u6zcPcwus8YnI+CjxpbWcgc3JjPQ=="/uploadfile/Collfiles/20141223/20141223105336405.jpg" alt="\">

代碼清單:
布局文件:activity_main.xml


    
        

        

    
    
        

        

    
    
        

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.


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved