我想用文件中的sharedPreferences将我的字符串信息保存为键值
答案 0 :(得分:3)
以下代码 显示如何创建和存储共享首选项数据:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","JITESH");
editor.putString("Password","password1234");
editor.commit();
以下显示了如何检索共享首选项数据:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name","");
String password = prefs.getString("Password", "");
此处显示的另一种做法是==>
显示了如何创建和存储共享首选项数据:
SharedPreferences prefs = getSharedPreferences("myDataStorage",
MODE_PRIVATE);
Editor mEditor = prefs.edit();
mEditor.putString("username","datastorageuser1");
mEditor.putString("password","password1234");
mEditor.commit();
以下显示了如何检索共享首选项数据:
SharedPreferences prefs = getSharedPreferences("myDataStorage",
MODE_PRIVATE);
String username = prefs.getString("username", "");
String password = prefs.getString("password", "");
更多访问我的博客
http://upadhyayjiteshandroid.blogspot.in/2013/01/android-working-with-shared-preferences.html
答案 1 :(得分:1)
获取共享偏好:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
阅读偏好:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
编辑和保存首选项:
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();
请参阅this