SharedPreferences是Android中存储一些轻量级(只能存储key-value对)数据的一种方式,实际上SharedPreferences会把数据保存在xml文件中,可以在/data/data/appPackageName/下查看对应的xml文件。
获取方式
Context对象的getSharedPreferences()和Activity对象的getPreferences()方法。
区别:
getSharedPreferences()获得的SharedPreferences允许该应用程序下的其他组件使用,而getPreferences()获得的SharedPreferences只能在该Activity中使用。
获取和保存数据
//MainActivity.java主要代码:
@Override
protected void onStart() {
super.onStart();
//获取数据
SharedPreferences sharedPreferences = this.getSharedPreferences("person", Context.MODE_PRIVATE);//person是文件名,对应到person.xml
EditText nameEditText = (EditText) findViewById(R.id.name);
String name = sharedPreferences.getString(R.id.name+"", "");
nameEditText.setText(name);
EditText ageEditText = (EditText) findViewById(R.id.age);
String age = sharedPreferences.getString(R.id.age+"", "");
ageEditText.setText(age);
}
public void saveSetting(View view) {
//保存数据
SharedPreferences sharedPreferences = this.getSharedPreferences("person", Context.MODE_PRIVATE);
Editor edit = sharedPreferences.edit();
EditText nameEditText = (EditText) findViewById(R.id.name);
edit.putString(R.id.name+"", nameEditText.getText().toString());
EditText ageEditText = (EditText) findViewById(R.id.age);
edit.putString(R.id.age+"", ageEditText.getText().toString());
edit.commit();
}
<!-- fragment_main.xml主要代码 -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/name"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/age" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/age"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/saveButton" android:text="@string/saveSetting" android:onClick="saveSetting"/>
操作模式
Context.MODE_PRIVATE:私有,覆盖。
Context.MODE_APPEND:私有,追加。
Context.MODE_WORLD_READABLE:公开读(其他应用可读)。
Context.MODE_WORLD_WRITEABLE:公开读写(其他应用可读写)。