Search code examples
androidbroadcastreceiversharedpreferences

Use Shared preferences from another class in Broadcast Receiver


I am new to android. I am using a SessionHandler class where i save the username from LoginActivity in shared preferences. I want to access this username from shared preferences in a class of broadcast receiver

Here is the code for SessionHandler class.

 public SharedPreferences getLoginPreferences() {
    // This sample app persists the registration ID in shared preferences,
    // but
    // how you store the regID in your app is up to you.
    return context.getSharedPreferences(
            LoginActivity.class.getSimpleName(), Context.MODE_PRIVATE);
}

public void storeLoginSession(String str_Name) {
    final SharedPreferences prefs = getLoginPreferences();
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("name", str_Name);

    editor.commit();
}

I want to access this name name here in startService().

  public class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
               startService();
        }
  }

   private void startService() {

    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
    strDate = sdf.format(c.getTime());
}

How can I get this value? I tried using context but not working. Can anyone please help me.


Solution

  • Best way to use SharedPreference is to wrap inside your custom Preference class like :

    public class YourPreference {   
        private static YourPreference yourPreference;
        private SharedPreferences sharedPreferences;
    
        public static YourPreference getInstance(Context context) {
            if (yourPreference == null) {
                yourPreference = new YourPreference(context);
            }
            return yourPreference;
        }
    
        private YourPreference(Context context) {
            sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
        }
    
        public void storeLoginSession(String str_Name) {
            SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
            editor.putString("name", str_Name);
            prefsEditor.commit();           
        }
     }
    

    Then you can get YourPrefrence instance from any class where contet is available using

    YourPreference yourPrefrence = YourPreference.getInstance(context);
    yourPreference.storeLoginSession(YOUR_STRING);