SharedPreferences cleared if remove the app from recent activity android - android

I'm using SharedPreferences in my project with MODE_PRIVATE, when i cleared the app from recent activity list, and opens the app again, all my preference data is cleared.
I'm using this class fro setting and getting preference.
public class Preferences {
private Context _context;
private SharedPreferences _preferences;
private Editor _editor;
private String prefName = "pref";
//=====
public Preferences(Context context){
_context = context;
_preferences = this._context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
_editor = this._preferences.edit();
}
//=====
public Preferences commit(){
_editor.commit();
return this;
}
//=====
public Preferences set(String key, String value){
_editor.putString(key, value);
return this;
}
//=====
public String get(String key){
return _preferences.getString(key, "");
}
//=====
public Preferences set(String key, int value){
_editor.putInt(key, value);
return this;
}
//=====
public int getInt(String key){
return _preferences.getInt(key, 0);
}
//=====
public Preferences setBoolean(String key, boolean value){
_editor.putBoolean(key, value);
return this;
}
//=====
public void removeKey(String key){
_editor.remove(key);
}
//=====
public boolean getBoolean(String key){
return _preferences.getBoolean(key, false);
}
}
can any one help me ...??

change your set method like this
public Preferences set(String key, int value){
_editor.putInt(key, value);
_editor.commit();
return this;
}
you don't need separate commit() into independent method.
good luck

this is another example, in this example i create a value that save my city name and when my app lunched i check for existing , if exist the value of that key returned to me.
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// define sp
sp=getSharedPreferences("test", Context.MODE_PRIVATE);
// get sp value if exist
if(sp.contains("EkbatanApp")){
String spResult=sp.getString("EkbatanApp", "");
}
}
//save key
public void SaveSettingOnClick(View v){
Editor editor=sp.edit();
editor.putString("EkbatanApp", "Borujerd");
editor.commit();
}

Related

SharedPreferencies have different values for the same key

I am having troubles using SharedPreferences in an Android app, and I need to get clear on it.
To avoid issues I have created a separated class for all maters regarding SharedPreferences to be used in the app.
This is the class:
public class SharedPreferencesClasMiPaciente {
SharedPreferences prefs;
Context context;
private static String PREFS = "MiPaciente";
public static SharedPreferences getPrefs(Context context){
return context.getSharedPreferences(PREFS,Context.MODE_PRIVATE);
}
public static void insertData(Context context,String key,String value){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.putString(key,value);
editor.commit();
}
public static void insertDataInt(Context context,String key,Integer value){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.putInt(key,value);
editor.commit();
}
public static void insertDataLong(Context context,String key,Long value){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.putLong(key,value);
editor.commit();
}
public static void insertStringSet(Context context,String key,Set<String> value){
getPrefs(context).edit().putStringSet(key,value).commit();
}
public static String retriveData(Context context,String key){
return getPrefs(context).getString(key,"no hay datos");
}
public static int retriveDataInt(Context context,String key){
return getPrefs(context).getInt(key,0);
}
public static long retriveDataLong(Context context,String key){
return getPrefs(context).getLong(key,0);
}
public static Set<String> getStringSet(Context context, String key){
return getPrefs(context).getStringSet(key,null);
}
public static void deleteData(Context context,String key){
SharedPreferences.Editor editor=getPrefs(context).edit();
editor.remove(key);
editor.commit();
}
}
I try to call this class every time I need to get or insert new SharedPreferences Data.
For now, to retrieve data inside a Fragment, I am using this code:
hayFotos = SharedPreferencesClasMiPaciente.retriveDataInt(getContext(),"hayFotos");
To insert data inside a Fragment, I am using this code:
SharedPreferencesClasMiPaciente.insertData(getContext(),"codigo_exploracion_actual",cod_exploracion);
To retrieve data in an Activity, I am using this code:
hayFotos = SharedPreferencesClasMiPaciente.retriveDataInt(this,"hayFotos");
To insert data in an Activity, I am using this code:
SharedPreferencesClasMiPaciente.insertDataInt(getApplicationContext(),"hayFotos",1);
This way is working but not always, there is another fragment where using the same methods, it is getting a different value for the same key:
hayFotos = SharedPreferencesClasMiPaciente.retriveDataInt(getContext(),"hayFotos");
Log.d("test shared","test shared hay fotos "+hayFotos);
At this case I am always getting the value 0 for key "hayFotos".
Is there a way to get SharedPreferences data on all fragments and activities inside an app?

How to get value from Shared preference in Fragment?

I have been searching for the correct answer everywhere, but couldn't find it anywhere. That is why I am posting this question, this may look very similar to other questions but I didn't find the answer to this yet. I have to retrieve the user data that was saved during the login on Android device and I want to use the same data in a fragment, I tried using several answers found on StackOverflow, none of them worked for me. Look at the code below, how can I get the user values into strings?
SharedPreferences preferences = getActivity().getSharedPreferences("mysharedpref",Context.MODE_PRIVATE);
String user_name = preferences.getString("user_id",null);
String password = preferences.getString("role", null);
I have to pass these string values to a URL, but it doesn't work. I also checked passing values manually, it's working. For example, if I take assign values to the above strings like
String user_name="admin";
String password="administrator";
Best way to use your SharedPrefernce is by using your appContext that is accessible to the whole App(Common SharedPrefernce and accessible Everywhere).
Define your SharedPrefernce instance in your Application class with get and set methods as below : (If you have not created the Application class then create one as below, This class is called at the start of your app)
public class Application extends android.app.Application {
private static Application _instance;
private static SharedPreferences _preferences;
#Override
public void onCreate() {
super.onCreate();
_instance = this;
}
public static Application get() {
return _instance;
}
/**
* Gets shared preferences.
*
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences() {
if (_preferences == null)
_preferences = PreferenceManager.getDefaultSharedPreferences(_instance);
return _preferences;
}
//set methods
public static void setPreferences(String key, String value) {
getSharedPreferences().edit().putString(key, value).commit();
}
public static void setPreferences(String key, long value) {
getSharedPreferences().edit().putLong(key, value).commit();
}
public static void setPreferences(String key, int value) {
getSharedPreferences().edit().putInt(key, value).commit();
}
public static void setPreferencesBoolean(String key, boolean value) {
getSharedPreferences().edit().putBoolean(key, value).commit();
}
//get methods
public static String getPrefranceData(String key) {
return getSharedPreferences().getString(key, "");
}
public static int getPrefranceDataInt(String key) {
return getSharedPreferences().getInt(key, 0);
}
public static boolean getPrefranceDataBoolean(String key) {
return getSharedPreferences().getBoolean(key, false);
}
public static long getPrefranceDataLong(String interval) {
return getSharedPreferences().getLong(interval, 0);
}
}
Declare the Application class in AndroidManifest.xml file with line android:name=".Application" as shown in below snippet:
<application
android:name=".Application"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
Now, How to store key-value:
Application.setPreferences("Key","String_Value");
How to fetch key-value:
String value_string=Application.getPrefranceData("Key");
You can now set-SharedPrefernce key-value and get-SharedPrefernce value from anywhere in the app using public Application class and the static get and set methods
Firstly create a SharedPreference.java Class.
public class SharedPreference {
Context context;
SharedPreferences sharedPreferences;
String user_name;
String password;
public SharedPreference(Context co) {
context = co;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getPassword() {
password = getStringInput("password");
return password;
}
public void setPassword(String password) {
this.password = password;
stringInput("password", password);
}
public String getUser_name() {
user_name = getStringInput("Username");
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
stringInput("Username", user_name);
}
public void stringInput(String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public String getStringInput(String key) {
return sharedPreferences.getString(key, "0");
}
}
Now go into activity or Fragment
example: I'm gone use it in MainActivity.java
public class MainActivity extends AppCompatActivity {
Prefrences prefrences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Dashboard");
prefrences = new Prefrences(MainActivity.this);
prefrences.setUser_name("Rishabh Jain");
prefrences.setUser_name("8369554235");
Log.e("Details",prefrences.getUser_name()+" "+prefrences.getPassword())
}
}
The output will be Rishabh Jain 8369554235.
Similarly, you can use this in any Activity or any Fragment
I guess you are trying to get values with different key. Get values with same key you put them with.
String user_name = preferences.getString(preferences.KEY_USERNAME,null);
String password = preferences.getString(preferences.KEY_PASSWORD, null);
----BUT----
And don't use singleton pattern for SharedPreferences it is very bad to use Context in singleton. It will crash your app. You can figure it out why.
Instead use static methods.
public class PreferenceUtil {
public static final String PASSWORD = "PASSWORD";
public static void setInt(Context context, int in, String key) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
editor.putInt(key, in);
editor.apply();
}
public static int getInt(Context context, String key) {
SharedPreferences settings;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(key)) {
return settings.getInt(key, 0);
} else
return 0;
}
}
And access it like this
int password = PreferenceUtil.getInt(getActivity(), PreferenceUtil.PASSWORD);

android static methods usage

I am developing an android application, In which I created one "SessionManager.java" which contains only static methods, in splash screen Activity only, I am creating the instance for "SessionManager ", Because it is the
fist activity in app, But in sometimes, I am getting null object reference ,
is it necessary to instantiate Class in every activity ?
Sample code
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public static void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified!");
}
public static void setMobile (String login_mobile) {
editor.putString("mobile", login_mobile);
editor.commit();
}
public static String getMobile() {
return pref.getString("mobile", "00");
}
}
sometimes in some activities , getMobile() method is returning null value, why ? can I check null value before return that ? please give me any suggestions, I stuck here.
If you are using it for storing values in shared preference then do it like this
public class AppSharedPreferences {
private SharedPreferences appSharedPrefs;
private SharedPreferences.Editor prefsEditor;
private static AppSharedPreferences appSharedPrefrence;
public AppSharedPreferences(Context context) {
this.appSharedPrefs = context.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public AppSharedPreferences() {
}
public static AppSharedPreferences getsharedprefInstance(Context con) {
if (appSharedPrefrence == null)
appSharedPrefrence = new AppSharedPreferences(con);
return appSharedPrefrence;
}
public SharedPreferences getAppSharedPrefs() {
return appSharedPrefs;
}
public void setAppSharedPrefs(SharedPreferences appSharedPrefs) {
this.appSharedPrefs = appSharedPrefs;
}
public SharedPreferences.Editor getPrefsEditor() {
return prefsEditor;
}
public void Commit() {
prefsEditor.commit();
}
public void clearallSharedPrefernce() {
prefsEditor.clear();
prefsEditor.commit();
}
public void setUserId(String userid)
{
this.prefsEditor=appSharedPrefs.edit();
prefsEditor.putString("user_id", userid);
prefsEditor.apply();
}
public String getUserId() {
return appSharedPrefs.getString("user_id","");
}
}
and then to use it in class do it like this way
appSharedPreferences=AppSharedPreferences.getsharedprefInstance(ActivityLogin.this);
and then call your method using appsharedPreferences.yourMethod();

How to retrive SharedPreferences, which where saved from another activity in Android?

I have situation in my app. Let's take two activities A & B . A is the main activity(which gets started when app is opened). B is started from A. I have a check box in B, who's boolean value using isChecked() method is assigned to a boolean called value & is saved to SharedPreferences. The code for saving to SharedPreferences is
SharedPreferences sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("value", value);
editor.commit();
Now I want to read this value from activity A(i.e the Main activity), during opening the app and depending on this value I need to perform additional operations.
The code I use to retrieve the value is
SharedPreferences sharedPreference=PreferenceManager.getDefaultSharedPreferences(this);
boolean value=sharedPreferences.getBoolean("value", false);
The problem is that I am not able to retrive this values in activity A.Since the value is not retrieved the operations depending on value are not carried out.Also no matter how many times I check the checkBox upon restarting the application CheckBox remain unchecked in activity B. What is the problem?
You can create singleton class that manage app's preferences (do not forget make your own YourAppSingleton class):
public final class PreferencesUtil {
private PreferencesUtil() {}
public static float getFloatValue(String key, float defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getFloat(key, defaultValue);
}
public static void setFloatValue(String key, float value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putFloat(key, value);
editor.commit();
}
public static long getLongValue(String key, long defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getLong(key, defaultValue);
}
public static void setLongValue(String key, long value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putLong(key, value);
editor.commit();
}
public static void setIntValue(String key, int value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static int getIntValue(String key, int defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getInt(key, defaultValue);
}
public static void setStringValue(String key, String value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();
}
public static String getStringValue(String key) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getString(key, null);
}
public static String getStringValue(String key, String defValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getString(key, defValue);
}
public static boolean getBooleanValue(String key, boolean defaultValue) {
SharedPreferences preferences = getSharedPreferences();
return preferences.getBoolean(key, defaultValue);
}
public static void setBooleanValue(String key, boolean value) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void clearValue(String key) {
SharedPreferences preferences = getSharedPreferences();
Editor editor = preferences.edit();
editor.remove(key);
editor.commit();
}
private static SharedPreferences getSharedPreferences() {
return YourAppSingleton.getInstance().getSharedPreferences(YourAppSingleton.getInstance().getString(R.string.app_name), Context.MODE_PRIVATE);
}
}
Application class:
public class YourAppSingleton extends Application {
private static YourAppSingleton instance = null;
public void onCreate() {
super.onCreate();
instance = this;
}
public static YourAppSingleton getInstance() {
return instance;
}
}

How to read/write a boolean preference

Edit: this code actually works. I had problem in the code that used it. Leaving it anyway in case anybody will find it useful.
I have a class with two methods to write and read a boolean persisted preference. However, if I write a new value and then try to read it, I still get the old value. Only if I kill the app and relaunch it, I do get the new value. Any idea what the problem is?
Context mContext;
....
public void writeFlag(boolean flag) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
editor.putBoolean("mykey", flag);
editor.commit();
}
public boolean readFlag() {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getBoolean("mykey", false);
}
public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()
public static boolean getBooleanFromSP(String key) {
// TODO Auto-generated method stub
SharedPreferences preferences =
getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ",
android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}//getPWDFromSP()
public static void saveBooleanInSP(String key, boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(" SHARED_PREFERENCES_NAME ", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}//savePWDInSP()
public class SharePref {
private static final String TAG = SharePref.class.getSimpleName();
private static SharePref mThis;
private Context mContext;
private SharedPreferences mPreference;
private SharePref() {
}
public static void init(Context context) {
if (mThis == null) {
mThis = new SharePref();
mThis.setData(context);
}
}
private void setData(Context context) {
mThis.mContext = context;
mPreference = mContext.getSharedPreferences(TAG, Context.MODE_PRIVATE);
}
public static SharePref getInstance() {
return mThis;
}
public void writeString(String tag, String data) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putString(tag, data).apply();
}
public String readString(String tag) {
if (mPreference == null)
mPreference = mContext.getSharedPreferences(TAG, Context.MODE_PRIVATE);
return mPreference.getString(tag, null);
}
public void writeBoolean(String tag, boolean data) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putBoolean(tag, data).apply();
}
public boolean readBoolean(String tag) {
return mPreference.getBoolean(tag, false);
}
public void clear(String tag) {
mPreference.edit().remove(tag).apply();
}
}
//In Activity
SharePref.init(this);
SharePref.getInstance().writeString("key","value");

Categories

Resources