数据存储之SharedPreferences
在使用SharedPreferences时老是提示ANR,在网上搜索了下,解决了。
下面是转载http://blog.csdn.net/kesenhoo/article/details/6532118
1.适用场合:类似于ini文件,用来保存程序的一些属性设置
2.使用方式:通过getSharedPreferences方法获得Preferences对象,获得editor对象,使用editor.put……()方法添加数据,最后通过commit()方法保存这些数据
ShardPreferences mState = this,getPrefersences();
ShardPreferences.Editor editor = mState.edit();
editor.putint("num",99);
editor.apply(); //注意这边官方推荐使用apply来替代commit()提交数据,这样可以避免引起ANR,commit()操作会需要在UI线程进行等待
- SharedPreferences preferences = getSharedPreferences("kesenhoo", Context.MODE_PRIVATE);
- String name = preferences.getString("name", "");
- int age = preferences.getInt("age", 20);
- nameText.setText(name);
- ageText.setText(String.valueOf(age));
3.读取参数:
- SharedPreferences preferences = getSharedPreferences("kesenhoo", Context.MODE_PRIVATE);
- String name = preferences.getString("name", "");
- int age = preferences.getInt("age", 20);
- nameText.setText(name);
- ageText.setText(String.valueOf(age));
4.保存参数:自动保存到XML文件,路径为/data/data/包名/shared_prefs文件夹下
5.注意事项:默认情况其他应用程序不可以访问本程序的SharedPreferences文件,如果需要访问其他应用程序的SharedPreferences的配置文件,可以使用如下方法:
关键点:学习如何构造其他应用的上下文对象
Context otherContext = getContext().createPackageContext("com.hoo.preferences",Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences preferences = otherContext.getSharedPreferences("kesenhoo", Context.MODE_PRIVATE);
//下面的包名应该是需要访问的其他程序的所在位置,并设置为忽视安全问题
- //下面的包名应该是需要访问的其他程序的所在位置,并设置为忽视安全问题
- Context otherContext = getContext().createPackageContext("com.hoo.preferences",
- Context.CONTEXT_IGNORE_SECURITY);
- SharedPreferences preferences = otherContext.getSharedPreferences("kesenhoo", Context.MODE_PRIVATE);
- String name = preferences.getString("name", "");
- int age = preferences.getInt("age", 20);
- Log.i(TAG, "name="+ name + ",age="+ age);
6.GetPreferences()与getSharedPreferences()的区别
To get a SharedPreferences
object for your application, use one of two methods:
getSharedPreferences()
- Use this if you need multiple preferences files identified by name, which you specify with the first parameter.getPreferences()
- Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
官方Demo:
- public class Calc extends Activity {
- public static final String PREFS_NAME = "MyPrefsFile";
- @Override
- protected void onCreate(Bundle state){
- super.onCreate(state);
- . . .
- // Restore preferences
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- boolean silent = settings.getBoolean("silentMode", false);
- setSilent(silent);
- }
- @Override
- protected void onStop(){
- super.onStop();
- // We need an Editor object to make preference changes.
- // All objects are from android.context.Context
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putBoolean("silentMode", mSilentMode);
- // Commit the edits!
- editor.commit();
- }
- }