How to retrieve data prior to running an activity - android

I have 2 fragments.
Fragment 1
Loads sharedpreference to display string
Fragment 2
Saves sharedprefence for string
Is it possible to retrieve that string in my first Fragment without running the second Fragment?

Yes, this is possible. You just need to make sure you are reading with the same key you used to write with:
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
// Reading from SharedPreferences
String value = prefs.getString("myKey", "defaultValue");
Log.d(LOG_TAG, value);
Note that we've assigned a defaultValue as the return value here. If there is no value with the key "myKey" in your shared prefs, it will instead return "defaultValue". This is a nice safeguard, think of it like a null pointer check - you will always get a value from getString(), even if it's just the default.
You don't need to be in the same activity for this to work, you just need to make sure that 1) your preferences name is the same and 2) the key used to store the value is the same in both spots.

First, don't get confuse between Activity and Fragment.
And yes, you can.

Related

Android sharedpreferences.getBoolean() returns the wrong, default value

On the picture you can see that the boolean variable took the default value, even though there was a key-value pair in the SharedPreferences with the right key. What can cause this? In the code this is at the end of an onCreate method. After this the onMapReady method gets called (from com.google.android.gms.maps.OnMapReadyCallback), where I check the SAME boolean value, to see If i have to place some markers on the map or not. In that method the getBoolean() behaviour is correct, the default value is ignored. This doesn't make any sense to me, anyone can help me out?
1) Did you intend the space in the key "isThereReservation " ? In your debug code, the variable doesn't have a space. Make sure you use the right key else you'll get the default value!
2) How are you saving the sharedPref? your code should be:
myPrefs = myContext.getSharedPreferences("MY_PREFERENCE_NAME", MODE_PRIVATE);
myPrefEditor = myPrefs.edit();
myPrefsEditor.clear();
myPrefsEditor.putBoolean("MY_KEY",myBool);
and then you can access by using:
myPrefs = myContext.getSharedPreferences("MY_PREFERENCE_NAME", MODE_PRIVATE);
myPrefs.getBoolean("MY_KEY",MY_DEFAULT_VALUE);
The method getBoolean return default value if the key doesn't exist. In your case, the default value is false and if the key of the SharedPreference doesn't exist is false in your case.
You are showing in debug the value of the HashMap mMap but what is the content of the eu.arrowhed.arrowheaddemo for the same key?

Shared Preference returns always the default value

Here is code I am Using to create and store value in Preference.
outgoing is String variable.
SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("PhoneNo","Hi");
editor.commit();
Here is the code to get value from SharedPreference.
SharedPreferences sp
=getSharedPreferences(outgoing,Activity.MODE_PRIVATE);
String calln = sp.getString("PhoneNo","0");
Toast.makeText(mContext, "SHARED"+calln,Toast.LENGTH_LONG).show();
You should probably call the getSharedPreferences on the context from which you are accessing them.
Source
Therefore, depending on how you can access your context, if you pass it to some other activity or in an asynchronous task, here are some examples of usage:
this.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
context.getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
Also, one way you can test your stuff is to use a listener when SharedPreferences get changed:
onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
Called when a shared preference is changed, added, or removed.
here is how to do that
You can also use the Preference Manager to obtain the SharedPreferences:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).getString(
"PhoneNo", "0");
Or to store them:
PreferenceManager.getSharedPreferences(YOUR_CONTEXT).edit().putString(
"PhoneNo", "Hi").commit();
The most likely reason that Shared Preference always returns the default value is that you saved the value in one preference file and then tried to retrieve it in another preference file. This can happen if you do call getPreferences() from different Activities, because getPreferences() creates a different preference file based on the activity it is created in.
Solution
The easiest solution is to always get your shared preferences like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
This will use a single preference file for the entire app.
Alternate solution
If for some reason you need to use different preference files, then you can do
final static String PREF_FILE_1 = "pref_file_1";
...
SharedPreferences sharedPref = context.getSharedPreferences(PREF_FILE_1, Context.MODE_PRIVATE);
Just make sure you always use the right file name for the preferences you are trying to save and retrieve.
Local preferences
If you really only need a preference for a specific Activity, then you can use getPreferences(Context.MODE_PRIVATE). Just don't expect to be able to retrieve the values from another Activity in the same way.
See also
This answer describes the differences between the various ways of obtaining SharedPreferences.
Difference between getDefaultSharedPreferences and getSharedPreferences
Mess with the shared preferences of android - which function to use?
change this Activity.MODE_PRIVATE to this Activity.MODE_MULTI_PROCESS, issue is probably due to different context during storing value and accessing value.
When putting values, try changing this:
SharedPreferences sp = getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
to this:
SharedPreferences sp = getApplicationContext().getSharedPreferences(outgoing, Activity.MODE_PRIVATE);
Same when getting values - don't forget to add getApplicationContext() in your call to SharedPreferences
EDIT:
Check that your "outgoing" String is the exact same in both Activities

How to display the server response on textview that should be displayed on all the screens in Header in android?

I want to display the server response on multiple screen in header bar in Android? Please, tell me how to do that? I created an abstract class and defined the Asynctask class. In onPostExecute method i am using the textview for displaying the result. Now my question is how all the activities access this textview?
I am new with Android. Please, give me the proper way to solve this?
May be you can use the shared preference feature of android to save the response.
References are How to use SharedPreferences in Android to store, fetch and edit values and http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
On each activity, you can set the header by referring the value from shared preference.
Create one base activity and extend that created base activity instead of activity. Create one xml file in base activity, in it only declare your header. nothing else, now to display use that xml and for the other contents you can use your actual xml file. So this one is for to set global header. Now, save your response to Shared preferences and use it throughout the app whenever you need.
Store the value into Shared preferences
SharedPreferences sharedPref = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
// saving
sharedPref.edit().putString("key", "value").commit();
// reading
sharedPref.getString("key", "default");
You need to store the response values in Stringbuffer
StringBuffer value =new StringBuffer("your response value");
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Identifier",value);
editor.commit(); //important, otherwise it wouldn't save.
Get the value in next activity
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
final String myVariable = prefs.getString("Identifier", "value");

Saving data between activities using external class

I'm developing an app that has to share strings between activities. I'm trying to get the seperate activities to call a public class with set and get methods. The calling the methods part works and I manage to get a response although the set value has to be rememberd by the set and get class. Here's a link to my set and get class, it's pretty basic: http://pastebin.com/0WabNKz3
Now my question is this: How do I make the set and get class to remember my values between sessions? Feel free ask questions if there's anything you didn't understand.
Thanks!
You need to use SharedPreferences. That's the way to save data even after the app is closed and you can access it from anywhere:
public void savePrefrences(String key, String value)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
prefs.edit().putString(key, value).commit();
}
public String getPrefrences(String key)
{
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), 0);
return prefs.getString(key, "");
}
Save the prefrence when and whereever you want and get it whenever and from wherver you want.
The value will not delete when you close the app.
I ended up creating invisible EditTextPreference that now hold the data that I want to keep because they can be shared easily.
When you say saving between sessions, do you mean between the app being paused, or closed completely?
A good resource for lifecycle and storing data across sessions is:
//developer.android.com/training/basics/activity-lifecycle/index.html

Acces Preferences From another class

I have an application which has a Prefernces Class and I want to know how could i make so that when the application is started the settings to be applied even before entering the preferences ( settings ) class. I have a getPrefs() void method which is called when i press "Save" Button in preference activity.
So, could you help me and tell what should I do the "default" preferences to be applied when entering the application ? (I need getprefs method from another class )
I would be grate if you could give me some advices or tips.Thank you !
To get an instance of the SharedPreferences from anywhere in your application use:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPrefences(context);
To set a value in the preferences, you need to call the editor for those preferences, then set the value for a key and finally commit the result. It can all be done in a single line:
prefs.edit().putString("myKey","myValue").commit();
This would store the string value myValue on a key named myKey and it will be accessible (after you commit) to any class if it has the application's context when it calls getDefaultSharedPreferences.
To retrieve the stored value you specify the key and a fallback value in case there is no preference set with that key:
prefs.getString("myKey","oops no value found");

Categories

Resources