Search code examples
androidbroadcastreceiversharedpreferences

Android Shared preferences


I Simply want to store String name ="Android" using SharedPreferences from one of the Activity of my Application and latter I want to retrieve this String in BroadcastReceiver Class of same Application.

I tried everything. please help me.


Solution

  • Follow the below code. Make one class called PreferenceData . In that class there are two methods . One is for store the string into shared preference and another is for get the string for shared preference.

    public class PreferenceData 
    {
        static final String PREF_STORE = "store_temp";
    
        public static SharedPreferences getSharedPreferences(Context ctx) 
        {
            return PreferenceManager.getDefaultSharedPreferences(ctx);
        }
    
        public static void setTempString(Context ctx, String str) 
        {
            Editor editor = getSharedPreferences(ctx).edit();
            editor.putString(PREF_STORE, str);
            editor.commit();
        }
    
        public static String getTempString(Context ctx) 
        {
            return getSharedPreferences(ctx).getString(PREF_STORE, "");
        }
    }
    

    How to Access it ?

    PreferenceData.getTempString(Pass Context);   // Get Shared Preference String
    PreferenceData.setTempString(Pass Context,"Android") // Set String to Shared Preference