Created
June 25, 2015 06:42
-
-
Save 2hamed/8419dfad40eaafa8dc4f to your computer and use it in GitHub Desktop.
PrefsUtil.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.content.SharedPreferences; | |
import android.preference.PreferenceManager; | |
/** | |
* Created by Hamed on 11/24/2014. | |
*/ | |
public class PrefsUtil { | |
public static final String PREFS_LOGIN_USERNAME_KEY = "__USERNAME__"; | |
public static final String PREFS_LOGIN_PASSWORD_KEY = "__PASSWORD__"; | |
/** | |
* 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); | |
SharedPreferences.Editor editor = prefs.edit(); | |
editor.putString(key, value); | |
editor.commit(); | |
} | |
public static void removePref(Context context, String key) { | |
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); | |
SharedPreferences.Editor editor = prefs.edit(); | |
editor.remove(key); | |
editor.commit(); | |
} | |
public static void saveToPrefsAsync(Context context, String key, String value) { | |
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); | |
SharedPreferences.Editor editor = prefs.edit(); | |
editor.putString(key, value); | |
editor.apply(); | |
} | |
/** | |
* 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, String defaultValue) { | |
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); | |
try { | |
return sharedPrefs.getString(key, defaultValue); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return defaultValue; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment