Getting data from sharedPreference to a specific activity - android

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 !!

Related

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.

Storing boolean datas and textview datas in 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.

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.

Is it better to pass data via intent or query the database when needed?

I am just wondering what would be the better way to handle data in several activities in android.
Say I had two activities, A and B, that hold some views. First I load some data from a SQL database and inflate the views in A. Now, I want to start activity B, which uses the same set of data as A did.
Is it better to pass the data via Intent (putExtra()) and then inflate the views or is it better to query the database again and then inflate.
I am not sure about that, because both approaches seem to have their disadvantages:
Querying the database takes more time /more resources
Putting extra data to the intent makes it more complex, because of putting and getting the data (especially when working with more activities)
Can someone give me some advice on what is the best practice?
As compare to DB Query use Intent.
And another way is, use one common class which will holds your data temporary.
There is various way to pass and get data. It is more useful to use Intent than DB query.
But there is another useful way is shared prefernce. Through which you can create,edit, delete data as well as can fetch data from any of the activity.
To create or edit shared preference:
String share_pref_file = "your_file_name";
SharedPreferences prefs1 = getSharedPreferences(
share_pref_time_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = prefs1.edit();
editor1.putString("your_data", data); //data is your variable
editor1.commit();
To fetch data:
String share_pref_file = "your_file_name";
SharedPreferences prefs = getSharedPreferences(share_pref_file,
Context.MODE_PRIVATE);
String strJson = prefs.getString("your_data", "");
To delete:
String share_pref_file = "your_file_name";
SharedPreferences prefs1 = getSharedPreferences(
share_pref_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs1.edit();
editor.remove(share_pref_file);
editor.clear();
editor.commit();

Categories

Resources