|
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76 |
sharedpreferences (共享参数):也是保存数据的一种方法,通常用于持久化数据(定期更新保存数据)类似ajax的定时刷新。示例代码(主要来源于黑马教程)如下:import java.util.Timer;import java.util.TimerTask;import android.os.Bundle;import android.app.Activity;import
android.content.SharedPreferences;import
android.content.SharedPreferences.Editor;import
android.util.Log;import
android.view.Menu;import
android.widget.EditText;public
class MainActivity extends
Activity { protected
static final String TAG = "MainActivity"; private
EditText et_title; private
EditText et_content; private
Timer timer; private
TimerTask task; private
SharedPreferences sp; @Override protected
void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_title = (EditText) findViewById(R.id.et_title); et_content = (EditText) findViewById(R.id.et_content); //得到系统的参数的保持器,类似于new文件对象,把内容保存在info.xml文件中 sp = this.getSharedPreferences("info", MODE_PRIVATE); String title = sp.getString("title", ""); String content = sp.getString("content", ""); et_content.setText(content); et_title.setText(title); timer = new
Timer(); task = new
TimerTask() { @Override public
void run() { Log.i(TAG,"定期保存数据"); String title = et_title.getText().toString().trim(); String content = et_content.getText().toString().trim(); //得到参数文件的编辑器. Editor editor = sp.edit(); //类似得到输出流. //通过xml文件来存储数据 editor.putString("title", title); editor.putString("content", content); //editor.putInt("intnumber", 333); //editor.putBoolean("booleanresuklt", false); editor.commit();//把数据提交到参数文件里面. 类似数据库的事务(commit,rollback) } }; timer.schedule(task, 2000, 5000);//每个5s执行一次任务 }}总结sharedpreferences的使用方法: 1)通过上下文环境(this)获取参数的保持器--> this.getSharedPreferences("info", MODE_PRIVATE);同时可以设置文件名与模式; 2)通过参数保持器获得参数文件的编辑器--> Editor editor = sp.edit();类似与java中普通文件的输出流,可用于文件写操作 (支持写各种不同类型的数据editor.putInt();editor.putString();...); 3)最后通过方法 editor.commit();把写好的数据一次性提交到指定的参数文件中(xml文件); PS:此示例中,除了要学会sharedpreferences的用法外,还要学习或者加深对Timer and TimerTask 的一般用法(java知识) |
sharedPreferences,布布扣,bubuko.com
原文:http://www.cnblogs.com/allenpengyu/p/3662225.html