Skip to content

Instantly share code, notes, and snippets.

@ayushhgoyal
Created July 20, 2015 07:28
Show Gist options
  • Save ayushhgoyal/20a629e59557621bda44 to your computer and use it in GitHub Desktop.
Save ayushhgoyal/20a629e59557621bda44 to your computer and use it in GitHub Desktop.
This class can be used to perform SharedPref operations without writing boiler plate code.
package com.dbws.cm.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Created by ayushhgoyal on 3/2/15.
*/
/**
* Created by ayushhgoyal on 9/10/14.
*/
public class ShpUtil {
/**
* Called to save supplied value in shared preferences against given key.
*
* @param context Context of caller activity
* @param key Key of value to save against
* @param value Value to save
*/
public static void saveToPrefs(Context context, String key, String value) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
Log.v("ShpUtils saving", "key: " + key + "\n value:" + value);
}
/**
* Called to retrieve required value from shared preferences, identified by given key.
* Default value will be returned of no value found or error occurred.
*
* @param context Context of caller activity
* @param key Key to find value against
* // * @param defaultValue Value to return if no data found against given key
* @return Return the value found against given key, default if not found or any error occurs
*/
public static String getFromPrefs(Context context, String key) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String defaultValue = "";
try {
Log.v("ShpUtils returning for key: " + key, sharedPrefs.getString(key, defaultValue));
return sharedPrefs.getString(key, defaultValue);
} catch (Exception e) {
e.printStackTrace();
Log.v("ShpUtils returning nothing", e.toString());
return defaultValue;
}
}
/**
* @param context Context of caller activity
* @param key Key to delete from SharedPreferences
*/
public static void removeFromPrefs(Context context, String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = prefs.edit();
editor.remove(key);
editor.commit();
LogWrapper.v("Removed key:" + key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment