Android数据存储--SharedPreferences存储
此处通过一实例来说明,实例内容来自Google+Android开发入门与实战一书第八章
此实例主要实现用SharedPreferences存储程序信息的功能,主要效果如下图所示:
1.当第一次运行程序时如图1所示,有两个输入框,并且输入框内是空的,输入内容并退出程序
2.当再次运行此程序时如图2所示,1中输入的内容回显到了输入框内. 说明数据得到了保存


图1 图2
编码:
1.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="SharedPreferences Demo" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText android:text=""
android:id="@+id/name_edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password:" />
<EditText android:text=""
android:id="@+id/password_edit"
android:layout_width="fill_parent"
android:password="true"
android:layout_height="wrap_content"/>
</LinearLayout>
代码解释:如上代码所示,使用LinearLayout 布局,加入三个用来做界面提示的文本框(TextView),两个输入框 (EditText)
2.编写DBSharedPreferences.java文件,此文件是入口类,程序运行会首先调用该类
package my.db;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
/**
* 程序中信息保存(如:输入框信息回显)
* @author wangxiaobo
*
*/
public class DBSharedPreferences extends Activity {
/** Called when the activity is first created. */
public final static String SETTINT_INFOS = "setting_infos";
public final static String NAME = "name";
public final static String PASSWORD = "password";
private EditText fill_name;
private EditText fill_password;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取组件
fill_name = (EditText) findViewById(R.id.name_edit);
fill_password = (EditText) findViewById(R.id.password_edit);
//获取SharedPreferences对象
SharedPreferences settings = getSharedPreferences(SETTINT_INFOS, 0);
//获取SharedPreferences中保存的信息
String name = settings.getString(NAME, "");
String password = settings.getString(PASSWORD, "");
//将取出的信息放入组件
fill_name.setText(name);
fill_password.setText(password);
}
//程序退出时保存EditText内容
@Override
protected void onStop() {
super.onStop();
SharedPreferences settings = getSharedPreferences(SETTINT_INFOS, 0);
settings.edit().putString(NAME, fill_name.getText().toString()).putString(PASSWORD, fill_password.getText().toString()).commit();
}
}
代码解释:SharedPreferences将数据保存在哪里了呢?
SharedPreferences是以xml文件的方式自动保存的,切换视图到DDMS,在其File Explorer中展开/data/data/<package name>/shared_prefs目录,其中有**.xml文件,可以导出来查看内容