Android数据储存之SharedPreferences

Android中SharedPreferences通常与Editor连用

接口SharedPreferences常用方法:

boolean contains(String str):判断SharedPreferences中是否包含key为str的数据;

abstract Map<String,?>getALL():获取SharedPreferences中所有数据;

String getxxxx(String str,xxxx defvalue):获取指定类型的key为str的值!如果没有找到,则返回 defvalue

SharedPreferences 对象的获取方法:

通过Context中的getSharedPreferences(String name,int mode);

1、第一个参数为SharedPreferences的名称!

2、第二个参数有如下几个值:

      (1)Context.MODE_PRIVATE   :指定SharedPreferences数据只能被本应用使用

  (2)Context.MODE_WORLD_READABLE:指定SharedPreferences数据可以被其他应用读取,但是不能写

  (3)Context.MODE_WORLD_WRITEABLE:指定SharedPreferences数据可以被其他应用程序读写

Editor 常用方法:

SharedPreferences.Editor  Clear(); 清空SharedPreferences中所有数据

SharedPreferences.Editor  putxxxx(String str,xxxx value) 向SharedPreferences中添加数据

SharedPreferences.Editor  remove(String str) 删除SharedPreferences中指定key为str的数据

boolean commit(); 增删改之后提交

获取Editor对象:

SharedPreferences.edit();

代码:

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
public class MainActivity extends Activity implements OnClickListener{
    private Button read,write;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setEvent();
    }
 
    private void setEvent() {
        write.setOnClickListener(this);
        read.setOnClickListener(this); 
    }
 
    private void initView() {
        write =(Button) this.findViewById(R.id.write);
        read =(Button) this.findViewById(R.id.read);
        preferences = this.getSharedPreferences("MySharedPreferences",Context.MODE_PRIVATE);
        editor = preferences.edit();
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.read:
            //contains(Stirng str)方法:查找该sharedpreferences中是否包含key值为str的值!
            boolean i = preferences.contains("ddd");
            if(i){
                String str = preferences.getString("ddd", "0");
                //Toast.makeText(this,""+str+"", 0).show();
            }else{
                Toast.makeText(this,"没找到该数据", 0).show();
            }
            Map<String, ?> map = preferences.getAll();
            for (Entry<String, ?> map1 : map.entrySet()) {
                Toast.makeText(this,"KEY="+map1.getKey()+"||||||VALUE="+map1.getValue(), 0).show();
            }
            break;
        case R.id.write:
            editor.putString("ddd",new Date().toString());
            editor.putBoolean("aa",false);
            editor.putFloat("ff", 13);
            editor.putInt("rr", 33232);
            editor.commit();
            break;
        default:
            break;
        }
    }
     
}

 

posted @   一天学点  阅读(242)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示