8.1 Android Basic 数据存储 Preferences SharedPreferences
SharedPreferences 存储方式
SharedPreferences 用来存储一些简单的配置信息。
-
新建项目SharedPreferencesDemo,编辑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="SharedPreferences demo"
/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Name:" />
<EditText android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Password:" />
<EditText android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:text="" />
</LinearLayout>
2. 修改类SharedPreferencesDemo
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
public class SharedPreferencesDemo extends Activity {
public static final String SETTING_INFOS = "";
public static final String NAME = "NAME";
public static final String PASSWORD = "PASSWORD";
private EditText field_name;
private EditText field_pass;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//find edittext
field_name = (EditText)findViewById(R.id.name);
field_pass = (EditText)findViewById(R.id.password);
//SharedPreferences
SharedPreferences settings = getSharedPreferences(SETTING_INFOS,0);
String name = settings.getString(NAME, "");
String pass = settings.getString(PASSWORD, "");
field_name.setText(name);
field_pass.setText(pass);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
SharedPreferences settings = getSharedPreferences(SETTING_INFOS,0);
settings.edit().putString(NAME, field_name.getText().toString())
.putString(PASSWORD, field_pass.getText().toString())
.commit();
}
使用getSharedPreferences()方法获取SharedPreferences对象,然后使用getString取得其中保存的值。
onStop()程序在退出的时候调用此方法。使用getSahredPreferences获取SharedPreferences对象,然后调用edit()方法使其处于可以编辑的状态,在使用putString保存值,最后使用commit()方法提交数据。
在DBMS中使用FileExplorer 可以看到保存的文件在 /data/data/[package_name]/shared_prefs下 SETTING_Inofs.xml文件。