Android中提供SharedPreferences来存储一些少量的用户配置信息。SharedPreferences通常以 键值对的方式进行数据存储的。在Android API中定义入下:
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.
model是文件操作的方式,常见的有四种:
1.MODE_PRIVATE 只用当前应用程序可以读取,是默认方式,值为0
2.MODE_WORLD_READABLE 无限制读取方式,其他应用程序也可以访问该数据,这种方式比较不安全,容易产生系统漏洞,Android API 17已经被废弃了,不提倡使用,值为1
3.MODE_WORLD_WRITEABLE 无限制写入方式,除当当前应用程序外,其他应用程序均可对文件进行写入,这种方式比较不安全,容易产生系统漏洞,Android API 17已经被废弃了,不提倡使用,值为2
4.MODE_MULTI_PROCESS 多进程操作模式,当应用程序有多个进程时,可以共享数据。
值为4
另外还需要讲的一点就是:使用SharedPreferences存储数据必须使用SharedPreferences.Editor对数据进行操作。先通过SharedPreferences.edit()得到的Editor对象,然后使用Editor的各种类型的put方法(比如putString(),putFloat(),putBoolean())向文件中添加数据,使用SharedPreferences.getString(String key,String defValue),方法获得文件中的数据。第一个参数是数据存入时的键,第二个参数是如果该键不存在的默认返回值。
:
下面是我写的一个实例程序:
在布局文件中添加两个TextView用来显示存入的数据。
主程序中SharedPreferencesActivity.java的代码:
package com.example.fileoperator;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
class SharedPreferencesUtil{
private SharedPreferences sp = null;
private SharedPreferences.Editor editor = null;
private Context context = null;
public SharedPreferencesUtil(Context context,String name){
this.context = context;
sp = context.getSharedPreferences(name, 0);
editor = sp.edit();
}
public void putValue(String name,String value){
editor = sp.edit();
editor.putString(name, value);
editor.commit();
}
public String getValue(String name){
return sp.getString(name, null);
}
}
public class SharedPreferencesActivity extends Activity {
private TextView text1 = null;
private TextView text2 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferenceslayout);
text1 = (TextView)this.findViewById(R.id.sharedtext1);
text2 = (TextView)this.findViewById(R.id.sharedtext2);
SharedPreferencesUtil sharedUtil = new SharedPreferencesUtil(this, "myvalues");
sharedUtil.putValue("name", "yangwan");
sharedUtil.putValue("passwrod", "123456");
text1.setText(sharedUtil.getValue("name"));
text2.setText(sharedUtil.getValue("passwrod"));
}
}
在这里我自己创建了一个封装了SharedPreferences接口的工具类SharedPreferencesUtil。直接对数据进行存储和读取操作。
最后的效果是: