首页 > 代码库 > Android存储之SharedPreferences

Android存储之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.


Android存储之SharedPreferences