0

So, I've been developing an app for a school project. Basically what it does is the user logs in using Instagram API. His token is saved in Shared Preferences so the user doesn't need to log in everytime he enters the app. The user full Instagram name is saved in Shared Preferences too once the user logs in the first time:

 SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                   editor.putString("full_name", Global.full_name);
                    editor.commit();

This is the code for saving the full_name in LoginActivity. I have debugged this part of the code and Shared Preferences in saving correctly all the data. The problem is when the user is already logged in (he logs in, closes the app and opens it again) and goes to the ProfileActivity a label which should get SharedPreferences full_name variable doesn't get it. Where is the code for retrieving the data:

  SharedPreferences editor = PreferenceManager.getDefaultSharedPreferences(ProfileActivity.this);
    String full_name = editor.getString("full_name",null);

txtNomeUtilizador.setText(full_name);

Is there any problem when I'm retrieving the data from Shared Preferences? Because when I debug it says that there is no "full_name" variable in Shared Preferences

  • you're not getting the same preferences you're saving. Instead of using ProfileActivity.this, use ProfileActivity.this.getApplicationContext() - posting this as an answer – rguessford Feb 19 '18 at 21:58

1 Answers1

1

When i tried to save to Shared Preferences with your code it didn't work. Change this code:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                   editor.putString("full_name", Global.full_name);
                    editor.commit();

to:

        SharedPreferences.Editor editor = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
        editor.putString("full_name", Global.full_name);
        editor.apply();

You tried to retrieve info with this code:

 SharedPreferences editor = PreferenceManager.getDefaultSharedPreferences(ProfileActivity.this);
    String full_name = editor.getString("full_name",null); 

Please try to change it to:

SharedPreferences prefs = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE);
 String full_name = prefs.getString("full_name", null);

Some info about shared references:

Android Shared preferences example

https://developer.android.com/training/data-storage/shared-preferences.html#java

yoav
  • 191
  • 1
  • 2
  • 10
  • It worked! Thanks. Can you tell me what was the problem with getApplicationContext? –  Feb 19 '18 at 23:15
  • There is no problem with getApplicationContext. the problem (in your saving code) was that you used prefs.edit() instead of sp.edit(). – yoav Feb 19 '18 at 23:39