Not getting the updated value of the shared preference in the service - android

I am storing some value to a shared preference from an activity which launched from a widget. If I retrieve that value from the service started from the same widget, it is not the updated one. I am getting the previous value had in the shared preference. Even i check that value in the shared preference xml, i sees the updated one there.
Why this is happening. I know that widget and activity are two process, is that the reason?​
SharedPreferences preferences = getSharedPreferences("preferences_target_value", Context.MODE_PRIVATE);
String targetValue = preferences.getString("preferences_target_value", "0");
System.out.println("targetValue "+targetValue);`

These values are cached per process.
If you are running on Android > 2.3 you must specify MODE_MULTI_PROCESS when you call getSharedPreferences (). If you are running on Android < 2.3 then it should just work correctly. If you are running on Android 2.3 then there is a bug in the shared preferences stuff and it doesn't work correctly across multiple processes no matter what you do.

use commit() after updating values, call this to have any changes you perform in the Editor
prefsEditor.commit();
change your code instead of this
SharedPreferences preferences = getSharedPreferences("preferences_target_value", Context.MODE_PRIVATE);
to this
SharedPreferences preferences = getSharedPreferences("preferance name", Context.MODE_PRIVATE);

In manifest file try removing
android:process=":my_process"
from service. Hope it will work.

Related

How to make android app data, app-wide available?

How can I make data available through my whole android app?
For instance, I want to display a user picture in the toolbar in every screen. Also, the name of the user is displayed in the navigation drawer in every screen.
Is a singleton the right approach for this? Or are other techniques better?
I have been googling a lot, but i can't find a good approach for my use case so far.
To use shared preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
to save in shared preferences:
editor.putString("tag", "save me please");
editor.apply();
to retrieve from shared preferences:
String s = preferences.getString("tag", "default_value");
Notes:
You can make your tags as string constants to make sure you are always using the same value.
If you use the editor for multiple values, always remember to add editor.apply() in the end, to actually apply your changes.
If you want the editor to write the changes synchronously, use editor.commit() instead. You can save any type of variable in the shared preferences, just use the appropriate method (instead of putString use putInt, putLong, etc - same with the getSring). More on Shared Preferences in the API here

Android Shared Preference Still visible after Deleting File

I am trying an application where I am using Shared Preference. When I delete the preference file from data/data/com.your.package.name/shared_prefs/mySharedPref.xml manually using Android monitor, still the app is able to read the preference values.
I am assuming that some how the value is retained in main memory of the phone. Am I correct & what is the viable solution to clear shared preferences totally leaving no traces. But one thing I want to clear preference only if the file is wiped. For this I need to check presence of file, Any other approach rather than checking with File class ?
I think this code must work
public static void clearAllPreference(Context context){
SharedPreferences prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
To remove specific values: SharedPreferences.Editor.remove() followed by a commit()
To remove them all SharedPreferences.Editor.clear() followed by a commit()
You use remove() to remove specific preferences, you use clear() to remove them all.
Checkout official documentation on SharedPreferences.Editor.

All shared preference values are not getting stored after kiling app

I am testing my app against Samsung Galaxy S4 and I am storing 3 values in shared preferences. My problem here is after killing the app only last value that was selected and stored in the shared preferences is getting retrieved and other values are not getting reflected.
I am retrieving the shared preferences values in onStart of the activity.
Below is code for shared preferences:
SharedPreferences StoreValue_button;
SharedPreferences.Editor Storevalues_button;
StoreValue_button=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Storevalues_button=StoreValue_button.edit();
if(peramount.isChecked()==true){
amount=true;
Storevalues_button.clear();
Storevalues_button.putBoolean("amount", amount);
Storevalues_button.commit();
}
In the above code there is a button and I am storing the button value once it is checked and reflecting same when activity is started again.
code in onStart
Setpref_Button=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(Setpref_Button.getBoolean("amount", amount))
{
peramount.setChecked(true);
}
In the similar way there are other 2 shared preferences which has the similar code.
My issue here is out of 3 shared preferences only last value is retained once app is started after killing it. I am unable to understand the behaviour.
After lot of hardwork... made the code to run correctly.... I followed below procedure.
I don't know some how default shared preferences doesn't store all values it is storing only one value..No idea of this behaviour...
So removed default shared preferences and took only Shared preferences with Mode_Private... one for one storing value... now everything is working fine..
Below is the code:
SharedPreferences StoreValue_button;
SharedPreferences.Editor Storevalues_button;
StoreValue_button= getSharedPreferences("button",MODE_PRIVATE);
Storevalues_button=StoreValue_button.edit();
amount=true;
Storevalues_button.clear();
Storevalues_button.putBoolean("amount", amount);
Storevalues_button.commit();

How to read other app's SharedPreferences (same user ID)?

Tested on Android 4.3. I have two apps, com.my.app.first and com.my.app.second. In my activity I want to read preferences from the other app. I chose to use the same user ID for both my apps:
android:sharedUserId="com.my.app"
I always load my preferences like this:
prefs = getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
Now, in my second app I do the following:
try {
Context context = createPackageContext("com.my.app.first", Context.CONTEXT_IGNORE_SECURITY);
// context.getPackageName() does indeed return "com.my.app.first"
// Note: Context.MODE_WORLD_READABLE makes no difference here!
prefs = context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
}
prefs.mFile erroneously points to /data/data/com.my.app.second/shared_prefs/MyAppPreferences.xml.
Obviously, the call to getSharedPreferences returns the preferences for the current app even though I used the context of the other app. What am I doing wrong? Please help!
Found the problem! This sure looks like a bug in the getSharedPreferences API. It turned out that a previous call to getSharedPreferences caused the other context.getSharedPreferences() call to return the previous instance - the current app's preferences.
The solution was to make sure that getSharedPreferences() was NOT called before reading the preferences of the other app.
Solved by just reading the old context again. Sounds like a cache to me too.
Context tempContext = context.createPackageContext(originalContext.getPackageName(),Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedInformationM2 = tempContext.getSharedPreferences("sharedInformation", Context.MODE_WORLD_READABLE);
You might want to make the SharedPreference created in App A MODE_WORLD_READABLE and use a common sharedUserId for both App A and App B. Like mentioned in the link,
http://androiddhamu.blogspot.in/2012/03/share-data-across-application-in.html
Since both your apps are running you can also solve this problem by setting shared preferences:
tempContext.getSharedPreferences("sharedInformation", Context.MODE_MULTI_PROCESS);

saving state of an android Application?

Which of the following is/are appropriate for saving the state of an Android application?
a. Activity.onFreeze()
b. Activity.onPause()
c. Activity.onStop()
d. Activity.onDestroy()
e. Activity.onFinish()
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
Why won't you just use SharedPreferences?
Anyways: i'd store the data in onPause(), depending on what these data items are. You probably already know that all items that have an id assigned in the R.java are automatically saved onPause() and restored onResume()? - but this is more or less useless anyways since this data is lost after the app dies completely...
assuming that you want so save other stuff that you might want to write to an DB or file, onPause() might be a good choice. as you can see in http://xenonite.net/news/android-activity-lifecycle, after onPause() is called, the OS might kill the app if there's memory needed for other things. so the data will be lost if you'd try to save it somewhere else (e.g. onStop())
but: make sure, that this saving produces not too much overhead, since onPause() is called on several occasions (e.g. screen rotates...)

Categories

Resources