Android Static Variables and Shared Preferences - android

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.

Related

how can I save the data that I passed from the second activity to main activity?

I am new to android studio. I am building an application using esp8266 to toggle pins the ip address and the port number are in the second activity I used SharedPreferences to save data in the second activity so that they remain saved every time I close the app. Then I send this data to the MainActivity. I need to save this data because I need to use it in the MainActivity just like the second activity. I want it to but I don't know. Can any body help me please. Thanks
Your question is not clear if you put the data in shared prefs so read it from the other activity
if you dont know haw to read from shared prefs
here answer to do so
How to use SharedPreferences in Android to store, fetch and edit values
I am not able to get your question , but what I understand from your question is , you are saving the data in shared preferences in the second activity and you want to access the same data in the MainActivity , since you will be saving the data using a key , you can fetch the same data using the same key in the MainActivity , for more details you can go through - http://developer.android.com/training/basics/data-storage/shared-preferences.html
Your question is not clear but i think this will help you
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
To get Values from another activity. For example your shared preferences class name is Session then to get values:
Session session=new Session();
HashMap<String, String> user = session.getUserDetails();
String user_name=user.get(Session.KEY_NAME);
And now you can use user_name anywhere in activity

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.

Save state of checkbox in single choice list while navigating to another activity

How can i Save state of checkbox in single choice list while navigating to another activity & come back to previous activity. Any code snippet would be appreciated. Thanx in advance
Just save the value in SharedPreferences.
Reference is here: http://developer.android.com/reference/android/content/SharedPreferences.html
Example here: http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html
You will want to save the current value each time it changes in a shared preference value.
and have initMethod called in onCreate() and perhaps onStart() as well that checks the to see if the value is set in the SharedPreferences and if so initialize to that value.
There are numerous tutorials on SharedPreferences, they are definitely the place to store this kind of data. Otherwise you would need to subclass the Application object which is not a good idea.
There are a couple of things you may want to do.
#1 Pass data into another activity
intent.putExtra("keyName", "somevalue");
We can add multiple entries here. This is a key,value pair. So to receive this data from the receiving activity we have to write this code
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}
Read more: http://getablogger.blogspot.com/2008/01/android-pass-data-to-activity.html#ixzz24FoEOTwH
#2 Using Shared Preferences
Tons of info on this.
Easiest way to store data in Android.
http://developer.android.com/guide/topics/data/data-storage.html#pref
http://www.slideshare.net/androidstream/sharedpreferences-tutorial
#3 Using SQLite DB
Databases are great, might be going to far for just saving a checkmark
http://developer.android.com/guide/topics/data/data-storage.html#db

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