简体   繁体   中英

sharedPreferences.getString() return null

Im trying to display the user email in a textView using SharedPreferences.

Shared preferences is created in loginActivity. I try to access it from mainActivity.

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!

Here is the code im using :

  • 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:

to save

SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();

to read it

SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);

This happens because your value is not stored in the shared preferences.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM