views:

91

answers:

2

I save preferences in one activities but not able to get saved preferences in other activity. I can access saved preferences in the same activity but not in other one. It is not giving me any error but always gibing null values in second activity.

Below is the code:

First Activity:
      public static final String PREFS_NAME = "MyPrefsFile";
    SharedPreferences.Editor editor;
editor.putString("token", access_token);
 editor.commit();

Second Activity:

      public static final String PREFS_NAME = "MyPrefsFile";
   SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);//getPreferences(0); 
     String restoredtoken = prefs.getString("token", null);
     if (restoredtoken== null) {
               ///doing some task;


            }
A: 

How is the editor and prefs created for your first activity?

Is PREFS_NAME the same?

Stephen Denne
This is not an answer and should have been posted as a comment.
aioobe
@aioobe if PREFS_NAME isn't the same, or isn't used, then that is the answer to ... er... what was the question?
Stephen Denne
+2  A: 

Your first activity should have:

android.content.SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
android.content.SharedPreferences.Editor editor = prefs.edit();
editor.putString("token", access_token);
editor.commit();

Some other suggestions:

  • You should use Context.MODE_PRIVATE instead of the magic number 0 in the call to getSharedPreferences().
  • In your new edit, you show you have two different static fields in each activity for PREFS_NAME. This should be a single variable in either one, or somewhere else, but should not be duplicated.
JRL
Yes you are correct.Thanks for valuable response.
Maneesh