All shared preference values are not getting stored after kiling app - android

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();

Related

How to save number of times a user has tapped on a view

I am designing a simple application that will count how many times a user has tapped on a imageView. My question is what would be the best way of saving and reading this file. Any suggestions? I am thinking something like using Parse.com's local database. I have tried it, but I could not get it working the way I wanted. I am still a beginner, so please not so fancy suggestions.
Try to save data in SharedPreference. SharedPreference works like database for application on device that will be stored until any one has unistall app from device.
To create sharedPrefernce-
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To store data -
prefs.edit().putInt("key", int_value).apply();
To retrieve data-
// use a default value
int l = prefs.getLong("key", default_value);
Simplest options is always thebest option, go with shared preferences
Here is simple tutorial from google http://developer.android.com/training/basics/data-storage/shared-preferences.html
It will store your data in application local file. Take a note of that there are different shared preferences in example getPreferences() will return file specific for activity you used this method. While getSharedPreferences() will return application global file.

Saving Shared Prefrences in Multiple instances

I would like to be able to save my users session or sharedPrefrences in a way that if the user kills the application and you start it it would look like this.
Button one = Start Activity with Blank Preferences
Button Two = List of Saved Sessions of Preferences and once clicked all put into the Starting activity.
Is this possible and if so how would I go about doing that?
Thank you!
Yes you can do that and it is good to use sharedPreferences if you just have to store some session variables. But if it is more, then go for database.
Do clear sharedPrefences in your application you need to do this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(activity);
Editor editor = settings.edit();
editor.clear();
editor.commit();
For reading the preferences, you can keep a sharedPreference with the count for the seesions. While saveing the prefences, always save with the strings session1, session2, session3 etc. So, while accessing them based on count, prepare a loop and form the string and access all the session variables and show them.
The reason why I didnt suggest you to do getAll() for sharedPreference is that, you may save few other things in sharedPreference. So by forming strings yourself, while reading you can just get the sessions and not other data saved in sharedPreference.
I hope you understand what I meant
Is this possible
I would say yes, depending on exactly what you mean.
if so how would I go about doing that?
SharedPreferences has a couple different functions to do something like this, depending on exactly what you want. You can get a Map of all preferences that are stored after clicking Button2 with getAll() or a set of preferences with a certain String such as "userName" or something similar with getStringSet(). Play around with the functions it offers and see if it gives you what you are looking for.
Also take not of the warnings of these functions
Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

can someone explain me how SharedPreferences works in Android in a very detailed yet easy understanding?

I'm novice in Android development and now I'd really like to learn Shared Preferences. I've googled it so many times and I don't think I quite mastered it.
I believe this Shared Preferences will help me to store username and a password on my login screen activity. Thanks you!
I made some videos about this as an audition for a job. They helped me get the job, and they're still available on Vimeo, so hopefully they can help you out.
Part 1: Saving Data
Part 2: Retrieving Data
Also, for what it's worth, be careful storing usernames and passwords in SharedPreferences. You can do it there, but read up on the risks in this other SO question: What is the most appropriate way to store user settings in Android application
For android, there are primarly three basic ways of persisting data:
shared preferences to save small chunks of data
tradition file systems
a relational database management system through the support of SQLite databases
SharedPreferences object help you save simple application data as a name/value pairs - you specify a name for the data you want to save, and then both it and its value will be saved automatically to an XML file for you. To save a data in sharedPreferences file:
Obtain an instance of sharedPreferences file:
SharedPreferences appPrefs = getSharedPreferences( or fileName, MODE_PRIVATE);
Create SharedPreferences.Editor object
To put for example a String value into SharedPreferences object use putString() method.
To save the changes to the preferences file, use the commit() method
That will look like this:
// obtain an instance of the SharedPreferences class
preferences = getSharedPreferences(prefFileName, MODE_PRIVATE);
editor = preferences.edit();
// save username String
editor.putString("username", student).commit();
To retrieve it use getString() method:
preferences.getString(username, null) where null is a default value that will be returned if username key is not found in the file.

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

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.

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