问题描述
我正在尝试使用 SharedPreferences 在 textView 中显示用户电子邮件.
Im trying to display the user email in a textView using SharedPreferences.
在 loginActivity 中创建共享首选项.我尝试从 mainActivity 访问它.
Shared preferences is created in loginActivity.I try to access it from mainActivity.
我使用 sharedPreference 的会话运行良好(登录布尔值保存在 sharedPreferences 文件中).
My session using sharedPreference work well (with a login boolean saved in sharedPreferences files).
怎么了?- 上下文错误?- 因为我尝试从另一个活动访问数据?
So what's wrong?- A context error?- Because I try to access the data from an another activity?
请帮忙:) 非常感谢!
Please help :) Thanks a lot!
这是我使用的代码:
登录活动:
Login Activity :
@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();
...
主要活动:
Main Activity :
@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);
}
推荐答案
读取存储的首选项你需要做的:
to read the stored preferences you need to do:
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);
这篇关于sharedPreferences.getString() 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!