How to Use Sharedpreferences in Android to Store, Fetch and Edit Values

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.

How to use shared preferences to save data that get from database?

First of all you have to create SharedPreferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_PREF_NAME", MODE_PRIVATE); 
Editor edt = pref.edit();

To add value in preference:

edt.putString("name", name);           
edt.putString("email", email);
edt.putString("alamat", alamat);
edt.putString("notelp", notelp);
edt.putString("username",username);

// Save your changes
edt.commit();

Now for getting data from preference:

String name=pref.getString("name", null);  
String email=pref.getString("email", null);
String alamat=pref.getString("alamat", null);
String notelp=pref.getString("notelp", null);
String username=pref.getString("username", null);

If you want to clear the preference data:

edt.clear();
edt.commit();

How to use SharedPreferences() to store value and get stored value to another activity

First intialize SharedPreferences with a Context:

final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(ApplicationLoader.applicationContext);

To save you could use this:

SharedPreferences.Editor editor = preferences.edit();
editor.putString("editText", yourEditText.getText().toString());
editor.commit();

Then to get the value inside another class, you could use:

String editText = preferences.getString("editText", "");

The second value "" represents a default value, if editText is not saved earlier, an empty String will be returned.

How do you save/store objects in SharedPreferences on Android?

You can use gson.jar to store class objects into SharedPreferences.
You can download this jar from google-gson

Or add the GSON dependency in your Gradle file:

implementation 'com.google.code.gson:gson:2.8.8'

you can find latest version here

Creating a shared preference:

SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

To save:

MyObject myObject = new MyObject;
//set variables of 'myObject', etc.

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

To retrieve:

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

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.

Creating a common Shared Preference class in android and using that class to fetch and set data from across all the modules in the project

Posting my answer here, this answer helped me, hope this would be helpful for you guys as well Thanks :)

public class SharedPref {

private static SharedPreferences mSharedPref;
public static final String PREF_NAME = "NG_CAD_FIRST_RESPONDER";
public static final String ACCESS_TOKEN = "ACCESS_TOKEN";
public static final String IS_READ_UNREAD_REQUIRED = "isReadUnreadRequired";
public static final String Access_State_Device = "accessStateDevice";


private SharedPref()
{

}

public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}


public static String getString(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}

public static void putString(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.apply();
}

public static Integer getInteger(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}

public static void putInteger(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value);
prefsEditor.apply();
}


public static boolean getBoolean(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}

public static void putBoolean(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.apply();
}

public static long getLong(String key, long defValue) {
return mSharedPref.getLong(key, defValue);
}

public static void putLong(String key, long value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putLong(key, value);
prefsEditor.apply();
}


public static float getFloat(String key, float defValue) {
return mSharedPref.getFloat(key, defValue);
}

public static void putFloat(String key, float value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putFloat(key, value);
prefsEditor.apply();
}


//// Clear Preference ////
public static void clearPreference(Context context) {
mSharedPref.edit().clear().apply();
}

//// Remove ////
public static void removePreference(String Key){
mSharedPref.edit().remove(Key).apply();
}

}

Fetching & Putting data in preference:

SharedPref.init(getApplicationContext());


SharedPref.getString("LATITUDE", ""));
SharedPref.putString("LATITUDE", latValue);


Related Topics



Leave a reply



Submit