作为android的5大存储数据的方式之一,sharepreferences还是具有其鲜明的特点的。
1.存储的数据一般比较小,比如是android的配置信息,用户名和密码之类的信息。
2.使用简单,不像操作数据库那么麻烦,写sql语句之类的。
3.采用键值对的形式存储数据。
下面是写在活动中的sharepreferences:
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
// 新建文件
SharedPreferences share = getSharedPreferences("test", 0);
// 处于能编辑状态
SharedPreferences.Editor edit = share.edit();
// 传入键值对
edit.putString("w", "hello");
edit.putInt("e", 1);
// 提交
edit.commit();
// 获取数据
String fir = share.getString("w", "");
int sec = share.getInt("e", 0);
text.setText(fir + "*****" + sec);
}
效果很简单,是在textview中打印存储的两个数据。
在非ui线程中访问sharepreferences:
ui线程:
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
GetShare share = new GetShare(this);
share.init();
String fir = share.getString();
int sec = share.getInt();
text.setText(fir + "*****" + sec);
}
先建个类,其中写明sharepreferences的新建和返回值:
/**
* 在非ui线程中获取分享文件
*
* @author hongjie
*
*/
public class GetShare {
private Context context;
private SharedPreferences share;
/*
* 初始化对象
*/
public GetShare(Context context) {
this.context = context;
}
public void init() {
// 新建文件
share = context.getSharedPreferences("test", 1);
// 处于能编辑状态
SharedPreferences.Editor edit = share.edit();
// 传入键值对
edit.putString("w", "hello");
edit.putInt("e", 1);
// 提交
edit.commit();
Toast.makeText(context, share.getString("w", ""), 1000);
}
public String getString() {
return share.getString("w", "");
}
public int getInt() {
return share.getInt("e", 11);
}
}
这样 ,就可以在需要的时候,在ui线程中访问这个类,从而来访问相关的数据。