1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package
com.example.android.active;
import
android.app.Activity;
import
android.content.Context;
import
android.content.SharedPreferences;
import
android.content.SharedPreferences.Editor;
import
android.os.Bundle;
import
android.widget.Button;
import
android.widget.EditText;
public
class
MainActivity6
extends
Activity{
private
EditText editText;
private
Button button;
private
SharedPreferences sharedPreferences;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
button=(Button) findViewById(R.id.test);
editText=(EditText) findViewById(R.id.EditText_main6_1);
//获取共享属性操作的工具(文件名,操作模式)
//MODE_PRIVATE/0,私有模式,只能本应用访问
//MODE_WORLD_READABLE(读)和MODE_WORLD_WRITEABLE(写)不建议使用(其他因公可以直接读取)
sharedPreferences=
this
.getSharedPreferences(
"data"
,
0
);
}
//在onPause()方法中编写保存数据的代码
//还原在onResume()方法中
@Override
protected
void
onPause() {
// TODO Auto-generated method stub
super
.onPause();
//读取信息数据(从xml文件中),写入editor
String msg=editText.getText().toString();
Editor editor=sharedPreferences.edit();
editor.putString(
"msg"
, msg);
editor.commit();
}
//在onResume()方法中编写还原代码
@Override
protected
void
onResume() {
// TODO Auto-generated method stub
super
.onResume();
editText.setText(sharedPreferences.getString(
"msg"
,
""
));
/*
* 删除信息数据(文件中的信息)
Editor editor=sharedPreferences.edit();
editor.clear();
editor.commit();
*/
}
}
|
本文转自 matengbing 51CTO博客,原文链接:http://blog.51cto.com/matengbing/1881434