Saving Shared Prefrences in Multiple instances - android

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.

Related

Android Static Variables and Shared Preferences

I am writing an android app and I retrieve a balance for the user from a webservice and the user is able to log in and out of my app.
When the app starts I check the shared preferences to see if the user is logged in or out. On correct log in I update the shared pref boolean to true and set it to false when the user logs out.
I need to know the balance in several fragments and I need to remember it when I am navigating thru the fragments in my app. When I return to the "My Account" fragment balance value is lost and I have to call my web service again to check it.
It the best way to use a string shared pref and update it any time the app starts or when there is a change in the balance. Or am I better to use a static variable in my main activity that can be referenced when the user navigates to the My Account fragment.
Is it possible to overuse shared preferences?
A simple and elegant solution is to use a very simple library TinyDB in android, which is nothing but an abstraction over the Shared Preferences.
You can initialise it in your activity's onCreate() method like this:
TinyDB tinydb = new TinyDB(this);
In fragment, just replace this with getActivity.
And then use it like this:
tinydb.putString("userName", "john");
String currentUser = tinydb.getString("userName");
Hope it helps.
For a single value such as balance or username you should definitely use SharedPrefereneces and OnSharedPreferenceChangeListener.
For structured data such as balance operations you should definitely use a database:
SQLite
Realm (noSQL)
StorIO (SQLite wrapper)
or some ORM.
There is 3 way to store you login details .
Using Shared Preference
Store Data in a File
Using Sqlite.
This tutorial will give you the ideas for storing login details.
You should store data in SharedPreferences rather than global variables because when app crashes, the data updated in static global variables at different times is lost and the default data in it remains.

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.

Is it possible to save a variable value in Android (in memory), even after closing the application? If so, how?

How is it possible to save a variable value in an Android app? Can the value be saved in memory? I am planning to save a float value in my application, so the next time the app is opened, the previous value will be loaded. How do I go about this? Shared Preferences or something else?
Yes. SharedPreferences is the best available option.
To store float value:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putFloat("storedFloat", storedFloatPreference); // value to store
editor.commit();
Also check this: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putFloat(java.lang.String,%20float)
Check this SO question. It nicely answers your question: How do I get the SharedPreferences from a PreferenceActivity in Android?
Yes its possible use shared preferences.
http://developer.android.com/reference/android/content/SharedPreferences.html
http://developer.android.com/guide/topics/data/data-storage.html#pref
You can also use sqlite data base to store the data and retrieve when you need it.
Your other storage options. you could store your values to a file in memory.
http://developer.android.com/guide/topics/data/data-storage.html
Look at the Storage Options Docs to be sure you pick the most appropriate type for you but if its just one value then SharedPreferences should work fine for you.
See The Docs for a good example on how to use SharedPreferences

Scope of SharedPreferences

I would like to know the scope of
SharedPreferences
. I want to set some variables which can be used in entire application all the time untill unless the application uninstalled by the user. Can I use SharedPreferences to save the value?? I know that I can use database, But I want to know the scope of SharedPreferences, so that I can use SharedPreferences properly. Somebody please help, Thanks in advance.
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings. This data will persist
across user sessions (even if your application is killed).
You can use SharedPreferences. If you curious about the life of SharedPreferences then its clear that it will be available for entire life of your application. But keep in mind that All application storage looses data when user clears the application data, so that time SharedPreferences will also loose the value.
Instead of using db, you can use SharedPreferences.
Ref : data-storage
you can use SharedPreferences to save variables within your application.
As a example you can use SharedPreferences in a game to save the score/points.
In this case if you are dealing with less number of variables i think the best way is
SharedPreferences.
Hope my answer helped you.
It is basically use small amount of data in key value pair form. And it will store all premitive type data with key value pair.
it is basically use to save password. session key, authuntication key etc.
SharedPreferences are stored in an .xml file, placed in your app's private data area.
The file's path is something like:
/data/data/PACKAGE_NAME/shared_prefs/PREFS_NAME.xml
and will be deleted only when the user uninstalls your app or clears the app data through Settings > Apps.
Can I use SharedPreferences to save the value?
Yes, you can use SharedPreferences to save any primitive value and retrieve it later on using the same key.
Parallel to SharedPreferences there's a persistance data which is not shared in the whole application but in an single Activity: Preferences. This is usefull to store values like filters parameters or temporary configurations.
Example from doc:
// SharedPreferences
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
// Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

How to attach a Preference to a particular SharedPreferences?

I am working on implementing the preferences for our application. I know how to display preferences UI and how to read/write values using SharedPreferences. In our app, I need to handle two sets of preferences and I would like to ask about this issue, one comment in the Android documents in particular.
The documentation for Preference.getSharedPreferences() has the following comment under the Return values section:
Returns The SharedPreferences where this Preference reads its value(s), or null if it isn't attached to a Preference hierarchy.
I would like to ask how it is possible to attach a SharedPreferences to a particular Preference, be it EditTextPreference or others. In other words, how does the persistence code in a Preference know that it should store the user input in one particular SharedPreferences object and not the other?
To explain my question further with an example, suppose I have the following:
SharedPreferences prefs1 = getSharedPreferences(file1, mode);
SharedPreferences prefs2 = getSharedPreferences(file2, mode);
My question is what API I should use so that prefs1 is used by the Preference objects' persistence code and not prefs2.
The target is Nexus One, running 2.3.4.
Maybe the answer is obvious but I could not find it after reading the documentation and searching the web. Thank you in advance for your help.
In other words, how does the persistence code in a Preference know that it should store the user input in one particular SharedPreferences object and not the other?
Preference uses PreferenceManager's getSharedPreferences(), which eventually routes to getDefaultSharedPreferences().
You are welcome to create your own Preference subclasses that change this behavior, but since the preference screen system may not be designed to handle multiple SharedPreference objects, there's a chance that your preference changes might not get persisted.
IOW, I encourage you to reconsider:
In our app, I need to handle two sets of preferences

Categories

Resources