Codementor Events

How to Save some string data in Shared Preferences in Android?

Published Aug 03, 2021

Declare following 2 methods:

Class CacheManager {
  public static void saveDataInCache(Activity activity, String key, String value) 	{
      SharedPreferences settings = activity.getApplicationContext().getSharedPreferences(Settings.getPrefsName(), 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putString(key, value);
      editor.apply();
  }

  public static String getDataFromCache(Activity activity, String key) {
      // Get from the SharedPreferences
      SharedPreferences settings = activity.getApplicationContext().getSharedPreferences(Settings.getPrefsName(), 0);
      String value = settings.getString(key, "");
      return value;
  }

  public static String getPrefsName() {
      return "SomeName";
  }
}

Now call like:

CacheManager.saveDataInCache(this, "SomeKey", "SomeValue");
String value = CacheManager.getDataInCache(this, "SomeKey", "SomeValue");
Discover and read more posts from Md. Najmul Hasan
get started
post comments1Reply
Mya Brown
10 months ago

The provided code exemplifies an effective approach for saving and retrieving string data using SharedPreferences in Android for https://uaesafari.ae/. The CacheManager class includes two commendable methods:

saveDataInCache: Commendably stores a string value in SharedPreferences with a designated key.

java

public static void saveDataInCache(Activity activity, String key, String value) {
SharedPreferences settings = activity.getApplicationContext().getSharedPreferences(Settings.getPrefsName(), 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.apply();
}
getDataFromCache: Admirably retrieves a string value from SharedPreferences based on the provided key.

java

public static String getDataFromCache(Activity activity, String key) {
SharedPreferences settings = activity.getApplicationContext().getSharedPreferences(Settings.getPrefsName(), 0);
String value = settings.getString(key, “”);
return value;
}
Additionally, the method for obtaining the SharedPreferences name is well-crafted:

getPrefsName: Effectively returns the SharedPreferences name.

java

public static String getPrefsName() {
return “SomeName”;
}
To implement these methods, simply follow this pattern:

java

CacheManager.saveDataInCache(this, “SomeKey”, “SomeValue”);
String value = CacheManager.getDataFromCache(this, “SomeKey”);

The consistency in method names is appreciated, ensuring clarity and ease of use. Well done.