Variable losing the value - android

I have a class where it contains a variable
public class MyClass
{
public static string testenome;
public string Testenome
{
get { return testenome; }
set { testenome = value; }
}
}
When I leave the application in the background I lose the value of the variable as soon as I return.
To some way for me to make that variable stay fixed, only if I close the app so I lose it ?

Yes you can do save that variable in SharedPreferences so as it stays in app memory even if its closed.
First set value in SharedPreferences
//MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "TestName");
editor.commit();
Now whenever you get back to app after closing it, just get the value of name from SharedPreferences
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
This is the best way to retain any such vairable until app is uninstalled.

Related

Android SharedPref not saving on restart

In my Android app I can display a popup when the app is updated (Based on versionCode). In the popup I have put a checkbox saying "dont show me again". When I click on that, it will save in the sharedpref the versionCode and wont display the popup anymore.
I have run against something odd behaviours where when I have saving the new Set<String>, it did indeed was saving it but when my app restarts the settings is lost.
Set<String> readAnnouncement = getReadAnnouncement(this);
readAnnouncement.add(String.valueOf(versionCode));
PreferenceManager.getDefaultSharedPreferences(this).edit().putStringSet(KEY_READ_ANN, readAnnouncement).apply();
If I break point on readAnnouncement.add, I can set for example the list having 2 items. When I execute the PreferenceManager.getDefaultSharedPrefer... and then execute getReadAnnouncement(this); the value is there, all good.
If I restart the app and check again getReadAnnouncement(this); the new value is gone.
By clearing the cache the problem disappeared... Why was is not saving? Is it possible the SharedPreference were full?
Try like this.
import android.content.Context;
import android.content.SharedPreferences;
/**
* #author VIVEK
* This class deals in with setting Cache value for complete app.
*/
public class SharedPrefUtil{
/*Set Boolean value in shared preferences */
public static void setSharedPref(Context context, String key, boolean value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
/*get Boolean value in shared preferences */
public static boolean getSharedPref(Context context, String key, boolean defaultVal) {
boolean prefToken = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
prefToken = sharedPreferences.getBoolean(key, false);
return prefToken;
}
/*Set String value in shared preferences */
public static void setSharedPref(Context context, String key, String value) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/*get String value in shared preferences */
public static String getSharedPref(Context context, String key, String defaultVal) {
String value = defaultVal;
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
value = sharedPreferences.getString(key, defaultVal);
return value;
}
public static void cleanSharedPrefFile(Context context) {
// save token in preference
SharedPreferences sharedPreferences = context.getSharedPreferences("usb", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
} // End of main class over here ...
Now you want to set some value in Shared Pref then set like this
SharedPrefUtil.setSharedPref(MainActivity.this, "test", storeBuff);
Now when you need to get value from shared Pref then call like this
SharedPrefUtil.getSharedPref(MainActivity.this, "test", "default value");
In place of editor.commit() , use editor.apply()
BASICS:
getDefaultSharedPreferences() uses a default preference-file name. This default is set per application, so all activities in the same app context can access it easily as in the following example:
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
if (spref.contains("email")) {
String sEmailAddr = spref.getString("email", "");
}
The preferences are usually stored at /data/data/com.package.name/shared_prefs/com.package.name_preferences.xml
The alternative method - getSharedPreferences(name,mode) requires to indicate a specific preference (file) name and an operation mode (e.g. private, world_readable, etc.), which allow to have better access over your SharedPref file.

Can't access sharedpreferences from other activity?

I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");

How to retain the value of String variables when activity is closed?

My string variables b,c,d,e,f stores the path of videos which I used in my gallery.But the problem is everytime my app shut down and restart again their values is lost and blank gallery is showed.I have tried making them static but through static they will retain the value for some time till the activity runs in background.Should I use onPause() and onResume() method so that they can retain their values.If yes plase suggest me code for that which i can use for retaining values of string variables when activity is closed.
SharedPreferences prefs = getSharedPreferences("bhu",0);
SharedPreferences.Editor editor = prefs.edit();
//Save the String value
editor.putString("val", b).commit();
editor.putString("val1", c).commit();
editor.putString("val2", d).commit();
editor.putString("val3", e).commit();
editor.putString("val4", f).commit();
b=prefs.getString("val", null);
c=prefs.getString("val1", null);
d=prefs.getString("val2", null);
e=prefs.getString("val3", null);
f=prefs.getString("val4", null);
You can use SharedPreferences to save the String values.
SharedPreferences prefs = getSharedPreferences(<Name>, <Mode>);
SharedPreferences.Editor editor = prefs.edit();
//Save the String value
editor.putString(<Key>, <StringValue>).commit();
Get the String value:
String str = prefs.getString(<key>, <DefaultValue>);
Please note that if you are not calling SharedPreferences in an Activity,you need to call getSharedPreferences through a Context.
[Edit]
if (prefs.getString("val", "Default").equals("Default")) {
editor.putString("val", b).commit();
}
Do it for other as well.

error in saving the username at the launch of application in android

I am developing an android application in which i have to do the following thing
At the start of the app, first thing it should do is ask user to enter name and then through a welcome screen with that name.
Then When the app is used next time it should just give welcome screen (should not ask for name again)
I have created the code for the above.
I have used shared preference saved
My code is
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
But how to check whetehr user is already registered?
Thanks
Tushar
But how to check whetehr user is already registered?
When user starts application first time that time you will check if any preference value exists for name key.
Following snippet will help you
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String namePrefrence = sharedPreferences.getString("uname", "");
if (namePrefrence.length() == 0) {
//User not registered!!
Show dialog where user will enter username
} else {
//User is registered!!
just show welcome screen
}
Well to use SharedPrefernces.. use this::
first declare it...
public static final String PREFS_NAME = "PrefernceNAme";
public static final String PREFS_ITEM = "PrefItemStored";
to get values from it, use:::
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
mode = preferences.getString(PREFS_ITEM, "PrefItemStored");
and to add values in SharedPrefernces, use::
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_ITEM, value)
.commit();

Android:implementing shared preference

I am making an app in which i have to save some string in shared preference and show it on another page means that i want to save name of user in shared preference in one activity and want to show the name of user on other activity.Any help regarding this will be appreciated.
Thanks
All you need to do is this (all the code is part of an acticity or Service (i.e. Context):
Get a SharedPreferences object:
static final String PREFS_NAME = "MyPrefs";
static final String USER_KEY = "user";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
To store a string:
String username = ...
SharedPreferences.Editor editor = settings.edit();
editor.putString(USER_KEY, username);
editor.commit();
To read:
String username = settings.getString(USER_KEY,null); // 2nd param is default value, used if prefs value is undefined
Here are more details: http://developer.android.com/guide/topics/data/data-storage.html
To achieve that first create one class, in that class you need to write all the function regarding get and set value in the sharedpreference . Please look at this below Code.
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static boolean getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Now you can first set the value of username from a prticular activity and get the value of user name from any activity.
You might wanna see this library. It's Secure and Easy to use.
https://prashantsolanki3.github.io/Secure-Pref-Manager/
Sample Code:
SecurePrefManager.with(this)
.set("user_name")
.value("LoremIpsum")
.go();

Categories

Resources