使用 SharedPreferences
SharedPreferences是一种轻量级的数据存储方式,学过Web开发的同学,可以想象它是一个小小的Cookie。它可以用键值对的方式把简单数据类型(boolean、int、float、long和String)存储在应用程序的私有目录下(data/data/包名/shared_prefs/)自己定义的xml文件中。
??? SharedPreferences接口主要负责读取应用程序的Preferences数据,它提供了如下常用方法来访问SharedPreferences的key_value键值对。
???
?package com.learn.android;import android.app.Activity;import android.content.Context;import android.content.SharedPreferences;import android.content.pm.PackageManager.NameNotFoundException;import android.view.View;import android.view.View.OnClickListener;import android.os.Bundle;import android.widget.Button;import android.widget.TextView;public class GetOtherSharedPreferencesActivity extends Activity {Button button;TextView view;Context othercontext;SharedPreferences sp; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button) this.findViewById(R.id.button1); view = (TextView) this.findViewById(R.id.view); try {othercontext = createPackageContext("com.learn.android",Context.CONTEXT_IGNORE_SECURITY);sp = othercontext.getSharedPreferences("preferences",othercontext.MODE_PRIVATE);} catch (NameNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} button.setOnClickListener(l); } OnClickListener l = new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString name = sp.getString("name","");int count = sp.getInt("count",0);view.setText("name="+name+"操作次数="+count);} };}
?
SharedPreferences的注意事项:
编辑完SharedPreferences一定要记得调用Editor的commit()方法,否则不会将数据写入到文件里的。
回顾总结:
1、? 如何得到SharedPreferences
SharedPreferences preferences=getPreferences(“test”,MODE_PRIVATE);
2、? 如何编辑SharedPreferences
得到Editor对象实例
SharedPreferences.Editor editor=preferences.editor();
3、? SharedPreferences的存储位置
/data/data/<package name>/shared_prefs
?
?