Skip to content Skip to sidebar Skip to footer

Android Studio - The Shared Perference Can't Be Saved On The New Activity

As the question suggested, the shared preference can't be saved on the new activity Set temp = getSharedPreferences('pref', MODE_PRIVATE).getStringSet('attempt', null

Solution 1:

To make your peferences global available I suggest to do a SharedPrefs.java class to save your SharedPreferences like this:

publicclassSharedPrefs {

publicstaticSharedPreferencesprefs(Context context){
    returnPreferenceManager.getDefaultSharedPreferences(context);
}

//Set your preferencepublicstaticvoidsetMyPreference(Context context, String text) {
    prefs(context).edit().putString("MyPreference", text).apply();
}

//Get your preferencepublicstaticStringgetMyPreference(Context context) {
    returnprefs(context).getString("MyPreference", "DefaultText");
}

And with the following code you can save data from your Activity as a SharedPreference to your SharedPrefs.java class:

//To save preferences in SharedPrefsStringmyString="Hello world";
                SharedPrefs.setMyPreference(getContext(),myString);

Or getting it from SharedPrefs.java to your Activity:

//To get preferences from SharedPrefs
                String getMyPreference = SharedPrefs.getCustomString(getContext());
                System.out.println(getCustomString);
                //Result = Hello world

Post a Comment for "Android Studio - The Shared Perference Can't Be Saved On The New Activity"