ApiDemos学习笔记App-Activity篇(7)——Persistent state

这个示例展示了存储数据的其中一种方式。通过使用Shared Preferences实现,程序退出后重新进入后,数据仍然保存在退出前得状态。

通过SharedPreferences.Editor对象实现对数据的存储,通过SharedPreferences对象取出SharedPreferences.Editor对象中的数据。针对所有基本数据类型,都有对应的储存和提取的方法。其参数与Map一样,都是通过“键”和“值”对应存储。

//程序重新启动后提取存储的数据
protected void onResume() {
super.onResume();

//SharedPreferences负责提取数据
SharedPreferences prefs = getPreferences(0);
//提取String
String restoredText = prefs.getString("text", null);
//如果Editor存储的String不为空,通过Editor存储的数据设置EditText的值
if (restoredText != null) {
mSaved.setText(restoredText, TextView.BufferType.EDITABLE);

int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
mSaved.setSelection(selectionStart, selectionEnd);
}
}
}

//程序退出好对数据进行存储
protected void onPause() {
super.onPause();
//Editor负责存储数据
SharedPreferences.Editor editor = getPreferences(0).edit();
//存储Srting,第一个参数为key,第二个参数为value
editor.putString("text", mSaved.getText().toString());
//存储int,第一个参数为key,第二个参数为value
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
//实现存储
editor.commit();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值