Android Getdefaultsharedpreferences

Android getDefaultSharedPreferences

Try it this way:

final String eulaKey = "mykey";
Context mContext = getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(eulaKey, true);
editor.commit();

in which case you can specify your own preferences file name (myAppPrefs) and can control access persmission to it. Other operating modes include:

  • MODE_WORLD_READABLE
  • MODE_WORLD_WRITEABLE
  • MODE_MULTI_PROCESS

PreferenceManager getDefaultSharedPreferences deprecated in Android Q

You can use the Android 10 support library version of PreferenceManager, i.e., androidx.preference.PreferenceManager and not android.preference.PreferenceManager.

Remember to add the following to your build.gradle:

implementation 'androidx.preference:preference:1.1.1'

How to use SharedPreferences in Android to store, fetch and edit values

To obtain shared preferences, use the following method
In your activity:

SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());

To edit and save preferences

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

Edit==>

I noticed, it is important to write difference between commit() and apply() here as well.

commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.

apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.

getDefaultSharedPreferences(getActivity()) in AsyncTask

use ActivityName.this instead of mContext

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ActivityName.this)

instead of

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext)

What is the file name used by default shared preferences?


private static String getDefaultSharedPreferencesName(Context context) {
return context.getPackageName() + "_preferences";
}

see your package name in AndroidManifest.xml



Related Topics



Leave a reply



Submit