Question

I am saving my username and password in shared preferences like so:

SharedPreferences sharedPref = Activity.this.getPreferences(Activity.this.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("login_username", "bla");
        editor.putString("login_password", ""bla bla"));
        editor.commit();

But I now need to access this value in a system service. Is there a way in which I can access this value? I would really prefer not to put these items in shared preferences as it will then be slightly less secure.

Was it helpful?

Solution

You can get your values like below:

    Context c = getApplicationContext();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
    String password = prefs.getString("login_password", "");
    String username = prefs.getString("login_username", "");

OTHER TIPS

Context mContext = getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);

Use the getString() method to retrieve the values: http://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String, java.lang.String)

Regarding the security, you should encrypt username/password before storing it into preferences. Shared Preferences (MODE_PRIVATE) cannot be accessed by other apps unless the device is rooted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top