2

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.

5 Answers5

5

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);
  • This is a perfect way, but i would suggest apply() instead of commit(), see here for why: http://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference It runs asynchronously, which is good! – so5user5 Apr 28 '16 at 10:51
1

You can create global functions for sharedPreferences:

public static void setSharedPrefString(Context context, String key, String value) {

    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preference.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getSharedPrefString(Context context, String key) {

    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
    if (preference != null) {
        return preference.getString(key, "");
    }
     return "";
}

call "getSharedPrefString" from onReceive of BroadcastReceiver. Let me know if you find it useful.

Rahul Parihar
  • 640
  • 7
  • 16
0

Create a class called AppPreference.class

public class AppPreference {

private SharedPreferences mSharedPreferences;

public static final String KEY_LOGIN= "KEY_LOGIN";


public AppPreference(Context context) {
    super();
    mSharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE);
}

public void setLoginStatus(String value) {
    SharedPreferences.Editor editor = mSharedPreferences.edit();
    editor.putString(KEY_POSTCODE_LOGIN, value);
    editor.commit();
}
public String getLoginStatus() {
    return mSharedPreferences.getString(KEY_POSTCODE_LOGIN,"");
}

}

You can save in value by calling

AppPreference appPreference = new AppPreference(context);
appPreference .setLoginStatus("value you want to save");

getvalue call

AppPreference appPreference = new AppPreference(context);
appPreference .getLoginStatus();
Nithinlal
  • 4,845
  • 1
  • 29
  • 40
0

Hi please use this sample code

public class PreferenceHandler { public static boolean storeNameToPrefernce(Context context, String key, String getDetailsString) {

    // TODO Auto-generated method stub
    SharedPreferences mySharedPreferences;
    try{
        mySharedPreferences=context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
        SharedPreferences.Editor editor=mySharedPreferences.edit();
        editor.putString(key,getDetailsString);
        editor.commit();
    }
    catch(Exception e){
        System.out.println(e);
        return false;
    }
    return true;
}
public static String getNameFromPreference(Context context,String key)
{
    String value;
    SharedPreferences mySharedPreferences;
    try{
        mySharedPreferences = context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
        value = mySharedPreferences.getString(key, "NONE");
    }catch(Exception e){
        return "NONE";
    }
    return value;
}

}

Getting string from Preference class:

In SampleActvity class.

String name =PreferenceHandler.getNameFromPreference(sampleActivity.this,key);

0

I do it in this simply way:

main class:

public class SWP extends Activity implements LocationListener
{   ....
    public static final String MY_PREFERENCES = "SWP_Preferences";
    public static SharedPreferences preferencesSwp;
    public static SharedPreferences.Editor preferencesEditorSwp;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {    ....
         preferencesSwp = getSharedPreferences(MY_PREFERENCES, Activity.MODE_PRIVATE);
         preferencesEditorSwp = preferencesSwp.edit();
         ....
    }
    ....
}

in any other, read

value1 = SWP.preferencesSwp.getString("PREF_value1", "init_text");

and write

SWP.preferencesEditorSwp.putString("PREF_value1", value1 );
SWP.preferencesEditorSwp.commit();
theWalker
  • 2,022
  • 2
  • 18
  • 27