Storing boolean datas and textview datas in android - android

I want to store a boolean variable and textview text on the device the app is running, so that even after clearing in recent apps i can use the recent booleab states to make changes remain the same. Or is there any way to get the last state even after clearing the app from the recent apps or onDestroy

You should check out Shared Preferences in Android.
Write to Shared Preferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read from Shared Preferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

#apelsoczi's answer is essentially correct, but here is a more detailed example which also includes boolean values, and String values, as asked in your question.
First get a reference to your apps Shared Preferences like this:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
Then save your string and your boolean like this:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(YOUR BOOLEAN KEY, YOUR BOOLEAN);
editor.putString(YOUR STRING KEY, YOUR TEXT VIEW STRING);
editor.commit(); // if commit is not called then data not saved!
To retrieve the values do this:
boolean b = prefs.getBoolean(YOUR BOOLEAN KEY, OPTIONAL DEFAULT VALUE IF ITS NOT FOUND);
String s = prefs.getString(YOUR STRING KEY, OPTIONAL DEFAULT VALUE IF ITS NOT FOUND);
Shared Preferences is a way to store simple key value pairs of data - very useful for settings. For example say you have a value false for your boolean, and you want to save it, so what you do is you pass in a name for it (passing a name is important because you need that name to retrieve the value) and the actual value to save. When you want to retrieve it, you again pass in the name you had assigned it when saving it.

Related

Getting data from sharedPreference to a specific activity

Is it possible to get a sharedprefence data from MainActivity_A and fetch it only to MainActivity_B and the other activities like MainActivity_C and MainActivity_D cannot access the data that has been fetched to MainActivity_B?
Well It totally depends on you wheather you wanna get that data or not..once you store data in shared preference with key then just get that data in the specific activity you want Thats It !!
For Example in Activity X you save the Shared Preference value like this
public static final String SHARED_PREFS = "sharedPrefs";
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("Key",Value);
Then in Activity A you want to use this value then you can do it like this
SharedPreferences pref;
pref = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
String Value = pref.getString("Key");
In This way the value will be stored in variable String
And if you don't want the value in other activity then just don't call it !!

How to add values from sharedpreferences to cardview in android?

I am using shared preference to store the user details. Now I want to get the value from shared preferences and to display it in cardview. I used
onBindViewHolder(final MyViewHolder holder,final int position)
method to pass data. How it possible to add shared preferences in adapter class?
You can get value by using this and later on you can bind with your componant
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
To get instance of SharedPreferences you need context. Pass context from activity/fragment to your adapter. Once you have context, get SharedPreferences instances as below :
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
Then you can use sharedPref to access your user details.
It will be better if you maintain an instance of your SharedPreferences at your app level so that you are not creating a new instance everywhere you need it.
private SharedPreferences preferences;
in constructor:
preferences = mActivity.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
now you can access it in onBindViewHolder
As shared preference is use for storing key value pairs and i am assuming you are using cardview with recyclerview, so you may need list of values.I think its bad practice and you can use sqlite for same purpose,if you want data from database or else you can get dynamically form api(if your app has backend).
You can use following code to get value from shared preference
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String value = (shared.getString(key, ""));
and set this string to cardviews value.

Is it possible to set the SharedPreference in the BroadcastReceiver?

I need to generate notification using BroadcastReceiver and need to save some data in the BroadcastReceiver class.
So, I used SharedPreference. But not able to save data inSharedPreference`.
SharedPreferences pref_date;
public static final String MyPREFERENCES = "MyPrefs";
pref_date = context.getSharedPreferences(MyPREFERENCES,context.MODE_PRIVATE);
_ed = pref_date.edit();
String t="hello";
_ed.putString(_date,t);
_ed.putString(flag,"0");
_ed.commit();
Yes, SharepPreference is just a kind of file that has key-value pairs to store and retrieve. You can access it from anywhere within the application. Even from the Services created by your application.
Hard to tell w/o looking into the source code, but most possibly you forgot to invoke the Editor's apply() or commit() method, like so:
mSharedPreferences.edit().putInt("some_int", 0).apply();
As per the documentation, this is how you should write to your SharedPreferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("yourKey", "stringToSave");
editor.commit();
And this is how you read:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "defaultValue";
String yourSavedString = sharedPref.getString("yourKey", defaultValue);
This is a working copy/paste example. Keep in mind that "yourKey" is used to identify your value, since SharedPreferences is key/value pair, so they have to match both when you read and write.

Android: Unbale to save boolean in SharedPreferences

Hey guys I am unable to save a boolean value using SharedPreferences. The value is ALWAYS true for some reasons. Here is how I save the value:
public static void setSharedPreference(Context ctx, String keyValue, boolean value){
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(keyValue,value);
editor.commit();
}
And this is how I get it back:
public static boolean getBooleanPreference(Context ctx, String keyValue){
boolean prefValue;
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, ctx.MODE_PRIVATE);
prefValue = sp.getBoolean(keyValue, false);
return prefValue;
}
What is wrong?!
Your code is syntactically correct, but I suspect you are passing different Context while saving than you are passing while reading from prefs. This will result in accessing different shared preferences storage. This is especially easy to step on if you are doing your writes and reads in different activities and decide to pass this as context. Unless there's a reason for doing so then you most likely want to reach your preferences from anywhere in your app then use always application context instead (getApplicationContext()).
Everything is correct in your code.
The ONLY possibility of a mistake is when you are calling these methods. Please use getApplicationContext() while putting and retrieving data.
And please do a "Clear data" for the app and start with a clean SharedPreference.

How to use one time domain name in android?

I have a RESTful web-service, I am retrieving a data to android device
So here My ip address/Doamin name may change like..
192.168.0.1 or1-255 etc or It may be www.stackexchange.com or www.stackoverflow.com
Like my data will be stored in 192.168.0.1/rst/api/login or www.stackoverflow.com/rest/api/sitemview
So to over come this I want to use domain name as One time when i install application
in my application I have other pages like Login,display list-view, Single ItemView.
So this domain name should stored in device and pass to other activities every time when I use.
I used shared preferences like
public static void savePreferences(Context ctx, String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
so when they load
public static Object loadSavedPreferences(Context ctx, String key) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
return sharedPreferences.getString(key, "");
}
So here My problem is that This one time value is not permanent when ever I force close or Restart devise that passing value is not working
Any suggetion
If your domain name fixed, use below code.
public class WS{
public static final String domain="http://blah.ws";
}
Access it in each activity
with
String apiPath=WS.domain+your_rest_path;

Categories

Resources