'Android - Using Shared Preferences in separate class?
I want to save data using Shared Preferences in android. But I am looking to use separate class to do this task. I have implemented that class like below,
import android.content.Context;
import android.content.SharedPreferences;
public class SavePref {
private Context context;
public SavePref(Context context){
this.context = context;
}
public void saveInt(String key, int value) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
}
But there is an error on getActivity(),
The method getActivity() is undefined for the type SavePref
How to solve this?
Thanks
Solution 1:[1]
getActivity() is a method of Fragment not of your SavePref. In your case the simple fix is to use the Context you are keeping as member variable to retrieve the SharedPreferences. An alternative to your approach is to avoid keeping the context as member variable, linking somehow the shared preferences to an instance of of your SavePref class, and have a static method
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPref = context.getDefaultSharedPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
and address the method like:
SavePref.saveInt(getActivity(), key, value);
from a Fragment or
SavePref.saveInt(this, key, value);
from an Activity. This way you don't need to instantiate SavePref every time you need to call saveInt, and you can avoid to store a reference to the Context.
Solution 2:[2]
I have created a class to do the same thing. This way you can save boolean, int, string data or check if data has been saved in a specific group of preferences for your app.
So, you need to create a class "DataProccessor.java" and put the content down bellow. Also I'm going to leave some examples about how to use it.
I hope it can helps you
import android.content.Context;
import android.content.SharedPreferences;
public class DataProccessor {
private static Context context;
public DataProccessor(Context context){
this.context = context;
}
public final static String PREFS_NAME = "appname_prefs";
public boolean sharedPreferenceExist(String key)
{
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
if(!prefs.contains(key)){
return true;
}
else {
return false;
}
}
public static void setInt( String key, int value) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(key, value);
editor.apply();
}
public static int getInt(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
return prefs.getInt(key, 0);
}
public static void setStr(String key, String value) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.apply();
}
public static String getStr(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
return prefs.getString(key,"DNF");
}
public static void setBool(String key, boolean value) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key, value);
editor.apply();
}
public static boolean getBool(String key) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
return prefs.getBoolean(key,false);
}
}
To use it I'll show you some small examples about how to save a String value in case you want to use it in an Activity, Fragment or Service.
For an Activity
//// To Save a value
DataProccessor dataProccessor = new DataProccessor(this);
dataProccessor.setStr("email","[email protected]");
//// To Retreive a value
dataProccessor.getStr("email");
For a Fragment
//// To Save a value
DataProccessor dataProccessor = new DataProccessor(getActivity());
dataProccessor.setStr("email","[email protected]");
//// To Retreive a value
dataProccessor.getStr("email");
For a Service
//// To Save a value
DataProccessor dataProccessor = new DataProccessor(getApplicationContext());
dataProccessor.setStr("email","[email protected]");
//// To Retreive a value
dataProccessor.getStr("email");
Solution 3:[3]
change
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
to
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
You already have context then why should you used getActivity()?
Actually getActivity() is used to get context in Fragment.
Solution 4:[4]
You can simple create the seprate Constant Class in Your Project and call it very simple way when you need to save or retrive the data..
class Constant {
companion object {
val loginData: String = "LoginData"
val token: String = "token"
//create the fuction of shared prefrence
fun setpref(context: Context): SharedPreferences {
return context.getSharedPreferences("Table Data", Context.MODE_PRIVATE)
}
}
}
Solution 5:[5]
package com.app.luandryuser.Util;
import android.content.Context;
import android.content.SharedPreferences;
public class DataStorage {
public static final int INTEGER = 1;
public static final int FLOAT = 2;
public static final int LONG = 3;
public static final int STRING = 4;
public static final int BOOLEAN = 5;
private Context ctx;
private SharedPreferences pref;
private SharedPreferences.Editor writer;
public DataStorage(Context ctx) {
this.ctx = ctx;
pref = ctx.getSharedPreferences("rural", Context.MODE_PRIVATE);
writer = pref.edit();
}
public void write(String key, int value) {
writer.putInt(key, value);
writer.commit();
}
public void write(String key, float value) {
writer.putFloat(key, value);
writer.commit();
}
public void write(String key, String value) {
writer.putString(key, value);
writer.commit();
}
public void write(String key, boolean value) {
writer.putBoolean(key, value);
writer.commit();
}
public void write(String key, long value) {
writer.putLong(key, value);
writer.commit();
}
public Object read(String key, int DataType) {
Object response = new Object();
if (DataType == INTEGER)
response = pref.getInt(key, 0);
else if (DataType == BOOLEAN)
response = pref.getBoolean(key, false);
else if (DataType == LONG)
response = pref.getLong(key, 0);
else if (DataType == STRING)
response = pref.getString(key, "");
else
response = pref.getFloat(key, 0.0f);
return response;
}
}
Solution 6:[6]
class PreferenceUtil {
private var msharedPref: SharedPreferences? = null
private var mEditor: Editor? = null
companion object {
private var sInstance: PreferenceUtils? = null
fun getInstance(context: Context): PreferenceUtils {
if (sInstance == null) {
sInstance = PreferenceUtils(context)
}
return sInstance as PreferenceUtils
}
}
constructor()
constructor(mContext: Context?) {
msharedPref = mContext?.getSharedPreferences(APP_PREF, MODE_PRIVATE)
mEditor = mSettings?.edit()
}
// get Boolean value
fun getValue(key: String, defValue: Boolean): Boolean {
return msharedPref!!.getBoolean(key, defValue)
}
// set Boolean value
fun setValue(key: String, value: Boolean) {
mEditor!!.putBoolean(key, value)
mEditor!!.apply()
}
}
// Initialize the Pref class in your required class
class Abc : AppCompatActivity() {
var mPreferenceUtil: PreferenceUtil = PreferenceUtils(this)
mPreferenceUtil.setValue(ABC_POPUP, false)
}
Solution 7:[7]
You can use this class :-
public class SharedPreferenceClass {
private static final String USER_PREFS = "SeekingDaddie";
private SharedPreferences appSharedPrefs;
private SharedPreferences.Editor prefsEditor;
// private String user_name = "user_name_prefs";
// String user_id = "user_id_prefs";
public SharedPreferenceClass(Context context) {
this.appSharedPrefs = context.getSharedPreferences(USER_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
//get value
public int getValue_int(String intKeyValue) {
return appSharedPrefs.getInt(intKeyValue, 0);
}
public String getValue_string(String stringKeyValue) {
return appSharedPrefs.getString(stringKeyValue, "");
}
public Boolean getValue_boolean(String stringKeyValue) {
return appSharedPrefs.getBoolean(stringKeyValue, false);
}
//setvalue
public void setValue_int(String intKeyValue, int _intValue) {
prefsEditor.putInt(intKeyValue, _intValue).commit();
}
public void setValue_string(String stringKeyValue, String _stringValue) {
prefsEditor.putString(stringKeyValue, _stringValue).commit();
}
public void setValue_boolean(String stringKeyValue, Boolean _bool) {
prefsEditor.putBoolean(stringKeyValue, _bool).commit();
}
public void setValue_int(String intKeyValue) {
prefsEditor.putInt(intKeyValue, 0).commit();
}
public void clearData() {
prefsEditor.clear().commit();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Blackbelt |
| Solution 2 | |
| Solution 3 | M D |
| Solution 4 | Constantin Beer |
| Solution 5 | Ankita Bhatt |
| Solution 6 | letmejustfixthat |
| Solution 7 | Debendra |
