Skip to content Skip to sidebar Skip to footer

Android - How To Get Data In A Shared Preference Of One Activity To Another Activity?

I have the following two activity I want to send the values present in'name' and 'subdivision' present in the shared preference to the second activity. I am able to get the values

Solution 1:

You're actually reading from two different preference files. Check this question.

these preferences

getSharedPreferences(PREFRENCES_NAME, Context.MODE_PRIVATE);

differ from these

PreferenceManager.getDefaultSharedPreferences(this);

Solution 2:

try this to set Shared Pref

String userId=yourstring,range=yourstring,subdivision=yourstring;
SharedPreferences settings = PreferenceManager
                    .getDefaultSharedPreferences(youractivity.this);
                Editor edit = settings.edit();
                edit.putString("name", userId);
                edit.putString("subdivision", subdivision);
                edit.putString("range", range);
                settings.commit;

to get shared pref

 SharedPreferences settins = PreferenceManager
            .getDefaultSharedPreferences(Youractivity.this);
 pref1=settings.getString("name", "anon");
 pref2=settings.getString("subdivision", "anon");

Solution 3:

Just did the following change and it worked, thanks Enrichman

SharedPreferences settings = getSharedPreferences("myprefrences", Context.MODE_PRIVATE);
        pref = settings.getString("name", "");
        pref2 = settings.getString("Subdivison",null);

Solution 4:

  1. In your first activity

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("NameOfShared", "Value");
    editor.commit();
    
  2. In your second activity

       final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String value=(mSharedPreference.getString("NameOfShared", "Default_Value"));
    

Post a Comment for "Android - How To Get Data In A Shared Preference Of One Activity To Another Activity?"