您的位置:首页 > 移动开发 > Android开发

android之-----SharedPreferences(存储数据)简单使用

2017-02-28 09:39 537 查看
作为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", "suzhen");
edit.putInt("e", 1);
// 提交
edit.commit();
// 获取数据
String fir = share.getString("w", "");
int sec = share.getInt("e", 0);

text.setText(fir + "*****" + sec);
}


效果很简单,是在textview中打印存储的两个数据。

下面给大家讲下在非ui线程中访问sharepreferences:

[java] view plain copy print?
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的新建和返回值:

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线程中访问这个类,从而来访问相关的数据。

不懂的可以留言或者私聊博主
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 存储 数据