2 回答
TA贡献1842条经验 获得超12个赞
解决方案:
这是存储和检索的简单示例 Shared Preferences
在首选项中设置值:
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
从首选项中检索数据:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
在您的情况下,您可能想要替换您的代码,如下所示:
尝试这个
SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();
editor.putBoolean("LoggedIn",true);
editor.putString(Constants.USERNAME,serverResponse.getMessage());
boolean ok= editor.commit();
然后在片段中
mSharedPreferences = getActivity().getSharedPreferences("prefs", MODE_PRIVATE); ;
mUsername = mSharedPreferences.getString(Constants.USERNAME, "");
如果要注销并删除用户登录,只需清除SharedPreferences:
SharedPreference.Editor pref = context.getSharedPreferences("prefs", MODE_PRIVATE).edit();
pref.clear();
pref.commit();
希望这可以帮助。
TA贡献1824条经验 获得超8个赞
尝试这个
SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();;
editor.putBoolean("LoggedIn",true);
editor.putString(Constants.USERNAME,serverResponse.getMessage());
boolean ok= editor.commit();
然后在片段中
mSharedPreferences = getActivity().getSharedPreferences("my_prefs", MODE_PRIVATE); ;
mUsername = mSharedPreferences.getString(Constants.USERNAME, "");
添加回答
举报