Android数据存储方式之SharedPreferences

鉴客 发布于 2011/11/14 14:19
阅读 11K+
收藏 3

【开源中国 APP 全新上线】“动弹” 回归、集成大模型对话、畅读技术报告”

在Android系统中提供了多种存储技术.通过这些存储技术可以将数据存储在各种存储介质上 Android 为数据存储提供了如下几种方式:

1、文件

2、 SharedPreferences( 参数 )

3、SQLite数据库

4、 内容提供者( Content provider

5、网络

在这里我们将对sharedpreferences存储方式进行介绍。

SharedPreferences是一种轻量级的数据存储方式,它可以用键值对的方式把简单数据类型(boolean、int、float、long和String)存储在应用程序的私有目录下(data/data/[包名] /shared_prefs/)自己定义的xml文件中。

SharedPreferences是以键值对来存储应用程序的配置信息的一种方式,它只能存储基本数据类型。一个程序的配置文件仅可以在本应用程序中使用,或者说只能在同一个包内使用,不能在不同的包之间使用。实际上sharedPreferences是采用了XML格式将数据存储到设备中,在DDMS 中的File Explorer中的/data/data//shares_prefs下。

下面我们以一个例子来说明如何使用sharedpreferences来存储数据,该例子是在Activity退出时保存界面的基本的信息,当再次运行该程序的时候,就会读取上次保存的信息。【界面中有一个账号EditText,密码 EditText和一个记住密码的CheckBox,输入账号和密码,如果选中记住密码复选框,下次打开程序时,则会显示账号和密码;如果没有选中记住密码复选框,下次打开程序时,则只是显示账号。】

res/layout/main.xml中的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="Welcome to Andy's Blog!"
       android:textSize="16sp"/>
    <LinearLayout
       android:orientation="horizontal"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content">
       <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="帐号:"/>
       <EditText 
          android:id="@+id/username"
          android:layout_height="wrap_content" 
          android:layout_width="fill_parent"/>
    </LinearLayout>
     <LinearLayout
       android:orientation="horizontal"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content">
       <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="密码:"/>
       <EditText 
          android:id="@+id/password"
          android:layout_height="wrap_content" 
          android:layout_width="fill_parent"
          android:inputType="textPassword"/>
    </LinearLayout>
    <CheckBox
       android:id="@+id/ischecked"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="记住密码"/>
</LinearLayout>

注:密码的EditText中的 android:inputType="textPassword" 属性标志该文本框输入的字符将以黑点来代替字符,表示为密码类型。

Activity中的代码如下:

package com.andyidea;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class TestDemo extends Activity {
	
	private final String PREFERENCES_NAME = "userinfo";
	private EditText username,password;
	private CheckBox cbRemember;
	
	private String userName,passWord; 
	private Boolean isRemember = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initializeViews();
        
        SharedPreferences preferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
		username.setText(preferences.getString("UserName", null));
		cbRemember.setChecked(preferences.getBoolean("Remember", true));
		if(cbRemember.isChecked()){
			password.setText(preferences.getString("PassWord", null));
		}else{
			password.setText(null);
		}
    }
    
    /**
     * 初始化UI控件
     */
    private void initializeViews(){
    	username = (EditText)findViewById(R.id.username);
    	password = (EditText)findViewById(R.id.password);
    	
    	cbRemember = (CheckBox)findViewById(R.id.ischecked);
    	cbRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				isRemember = isChecked;
			}
		});
    }
	@Override
	public void onStop() {
		super.onStop();
		SharedPreferences agPreferences = getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = agPreferences.edit();
		
		userName = username.getText().toString();
		passWord = password.getText().toString();
		editor.putString("UserName", userName);
		editor.putString("PassWord", passWord);
		editor.putBoolean("Remember", isRemember);
		editor.commit();
	}   
    
}

运行效果如下:

 

以上的程序是通过创建一个 userinfo.xml 文件来存储用户退出时保存用户的一些基本信息。当再次打开程序时,是通过读取该文件来获取之前的信息。

说明:使用SharedPreferences存取数据

保存key-value对一般要指定一个文件名,然后用类似putString的方法指定key和value。SharedPreferences也采用了同样的方法。使用SharedPreferences保存key-value对的步骤如下:

(1) 使用Activity类的getSharedPreferences方法获得SharedPreferences对象。其中存储key-value的文件名的名称由getSharedPreferences方法的第一个参数指定。

(2) 使用SharedPreferences接口的edit获得SharedPreferences.Editor对象。

(3) 通过SharedPreferences.Editor接口的putXXX方法保存key-value对。其中XXX表示value的不同数据类型。Boolean类型的value则是用putBoolean方法,字符串类型的则为putString方法。

(4) 通过SharedPreferences.Editor接口的commit方法保存key-value对。Commit方法相当于数据库事务中的提交(commit)操作。只有在事件结束后进行提交,才会将数据真正保存在数据库中。保存key-value也是一样。

文章出处:http://blog.csdn.net/cjjky/article/details/6460165

加载中
0
陈左东
陈左东
问LZ个问题,应用中搜索记录的存储是否可以通过SharedPreferences方式进行缓存,或是应该通过其他方式?
0
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部