我尝试使用SharedPreferences在textView中显示用户电子邮件。
共享首选项在loginActivity中创建。 我尝试从mainActivity访问它。
我使用sharedPreference的会话运行良好(登录布尔保存在sharedPreferences文件中)。
那有什么不对? - 上下文错误? - 因为我尝试从另一个活动访问数据?
请帮忙:)非常感谢!
以下是使用的代码:
登录活动:
@Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
...
//Creating a shared preference in a login()
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
...
主要活动:
@Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
email_session = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Private");
usernameText.setText(email_session);
}
答案 0 :(得分:0)
阅读您需要执行的存储偏好设置:
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);
答案 1 :(得分:0)
这是因为您的值未存储在共享首选项中。
SharedPreferences pref = getSharedPreferences("your Pref Name", 0) // 0 for Private Mode
String name = pref.getString("your key store when login", null); // null is the default value you can put it here "No value". then you will not get null pointer.