This question is more like a discussion about how you guys would do it.
I'm developing an application that has an Avatar Creation, but this creating occurs across two different Activities.
In the first one the user selects whether is man or a woman and a name, in the next Activity the user has to select his face, hair, clothes and etc.
Since the views for hair and etc changes if the user is a man or a woman how would you implement a way to pass the gender value to all the Views?
I was thinking about using a static member to hold the value so I could access inside my views, or maybe I should use SharedPreferences to do it.
I think using the SharedPreferences is a more elegant way to do it but I'm wondering if there isn't any other better and more elegant way of doing it.
Has anyone thought about other implementations?
If its only a small information like "gender" i don't see much harm using "Static" variable(Ofcourse the static variable will become null if your app crashes when its in the background).
SharedPreference will come good if you want the information to be persistent(But i don't see you need this).
One more choice is you do can extend the application class to store the static data across activities.
You could pass the gender to the next Activity with start activity Intent. Example:
Intent intent = new Intent(this, NEXT_ACTIVITY.class)
intent.putExtra("gender", genderVariable)
startActivity(intent);
And retrieve the value in NEXT_ACTIVITY class on onCreate() like this:
String genderVariable = ""
Bundle parms = getIntent().getExtras()
if (parms != null) genderVariable = parms.getString("gender")
Then, pass gender to all your views and persist the genderVariable on SharedPreferences or onSavedInstanceState bundle. I prefer onSavedInstanceState.
Hope it helps.
I think there are many ways of which 4 I think are better. It ofcourse depends on what kind of data you want to store.
For Lists or hashmaps, using a singleton class would be helpful.
Using a static class would help, but might leak memory. You should be very careful and always check using logcat, MAT before releasing your app.
Using preferences or database.
Passing data as Intent extra (parcelable if needed).
Using SharedPreferences would be the better way to share some global values across the application.
Related
My application has a list of clients (with only name and age displayed) and I want to be able to edit/add more info about them that is not visible in the list.
So whenever I click on a client, I want to start a second activity with all the info about him.
Can I use an intent for this? Can I pass a full Object (Client) at once with an intent?
I've looked through these two topics, but I haven't found my answer yet:
How to exchange data (objects) between different Android Activities?
How do I pass data between Activities in Android application?
Thanks in advance.
Look at this answer: How to pass an object from one activity to another on Android
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
I would suggest you look into saving these in the SharedPreferences file. Build a singleton AppUtil class and add functionality to save data in the shared preferences there as well as being able to retrieve said data
If you have a large amount of information being stored for the clients then you should look into SQLite as database storage.
The more pratice way is create a class to hold every objects that you need to change between the activities. Like that:
public class MyHolderObjects {
public static MyObjectType mObject;
}
before start the new activity (or whatever you goes to use it), instantiate (create) the object in MyHolderObjects. And use it everywhere you need :). I prefer this approach instead serialize the object.
Is possible to define, in Android, variables that are shared between more Activities? I tried to use "special purpose" classes, but i was looking for the best-pratice.
I already looked for similar questions, but i didn't find an exact answer to this question.
If you're looking to send a variable from 1 activity to the next, put it in the Intent. If you really have data that needs to be shared between all activities (such as login information or key data structures used by most/all activities) then you should use a singleton pattern.
Android already has a default singleton..its the Application class..you will extend that class and put some global variables in it taking care not to delcare theme static and to only use sparingly
If the data you plan to share between all Activities are small key-value pairs, you can store them in DefaultSharedPreferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (prefs.getBoolean(C.PREF_BACKGROUND_UPDATE_ENABLE, false)) {
// do smth useful
}
Is there any disadvantage in transferring values from Activity A to Activity B with static fields of a third class instead of the ExtraBundle?
In my application, sometimes I have like 15 - 20 values that I need to transfer between two Activitys. In my oppinion, it is more lucid solving this with static fields from a sort of TransferHandler.
At the moment, I have one disadvantage in mind: When a value is not put into the Extras before starting Activity B, I will get an Exception. Solving it with static fields, it it possible that I forget to assign a value, and if that value was assigned before from somewhere else, it might be that a wrong value is used in Activity B. Nonetheless, I think this is a "programmer problem" and not a "program problem". So are there any further minusses or am I free to choice a way? How's with the performance of the two variants?
First of all, if you plan to use static values, you should use your Application class to do this (because Android system assures you that it is a true singleton)
Thus, you can store your datas in attributes of your custom Application class, and use specific methods to store and get these values.
This will ensure you can't "forget" any values.
Also, with 15-20, I will strongly advice you to make a specialized POJO class to store all this...
I think the biggest disadvantage with using static classes for passing information in android is that static fields and objects can be cleared by the system at any time. That means that any static non final value can ALWAYS be null.
So it will probably work fine most of the time, but if you don't make sure to handle these null situations and your users start using your app they'll get a null pointer exception crash once in a while because the system decided it needed that memory stored in those static fields.
The best way for passing data between activities is by my opinion by using Intents, see here for a good example. Alternatively use a database or the the sharedpreferences.
Google also have a good read about pass data between Activities/Services here.
You cannot use a third class to transferring values form one activity to other. Here is the problem with it. You create one object in the activity-a then you store some values into it. Then after for using the values you need to create one more object in the activity-b then the object created in activity b will not be having the values you assigned in activity-a.
You can use SharedPreferences class to store valuo of variables:
SharedPreferences settings = getSharedPreferences("shared_pref", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = settings.edit();
// With editor you put data
editor.putString(firstName, "John");
editor.putString(lastName, "Smith");
editor.commit();
You can access this data in all activities:
// With settings you access to data in different activities
SharedPreferences settings = getSharedPreferences("shared_pref", MODE_WORLD_READABLE);
String firstName = settings.getString(firstName, null);
String lastName = settings.getString(lastName, null);
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
I need to pass a List of my objects between activities. I do not want to use parcelable or serialize the data each time. I also do not want to save it in a local file or database. That probably leaves me with using static objects.
Lets say I to use ListA between activities Activity1 to Activity2. I ca
Approach1: Create a static ListA in one of those activities and do all my stuff of that static ListA.
Approach2: Create a static list in another class which I use just for storing this List and doing all my stuff on this list. But this means that this stays as long as my process is running and I have to manually set it to null when I do not need it.
Approach3. I am extending the above class to implement it using a static HashMap.
I have two methods one to store the list in a static HashMap using a unique key and another method to retrieve the list and remove it each time data is retrieved so that the List is no longer present in the static HashMap. So we essentially have to pass only the random key generated to store data between activities which I can pass as an extra using Intents.
Will there be any issues when I use any of the above approaches and which will be the best approach.
I'd consider creating an Application object and using it like a singleton to access your data. I've described the approach here: http://chrisrisner.com/31-Days-of-Android--Day-7%E2%80%93Sharing-Data-Between-Activities. Some people don't seem to like using the Application object in this manner but it makes more sense to me than putting a static object on an Activity.
Uggg statics! Man I wish all developers understood global variables are bad and how they make your program more brittle and your life hell. We only been talking about how bad they are for 30+ years, but unfortunately no one figures this out until they've utterly hung themselves on them.
First I'll say serializing your data is fast. There are great tools out there that will serialize your objects quickly that you can use I prefer http://flexjson.sourceforge.net for this.
So if you are just outright opposed to this you can pass this object through the Application by subclassing it, declaring your implementation in your Android Manifest, and each activity has access to the Application instance:
public class MyActivity extends Activity {
public void onCreate( Bundle bundle ) {
MyApplication application = (MyApplication)getApplication();
Object anInstanceFromAnotherActivity = application.getSomeInput();
}
}
The downside to this is when your application is reclaimed if the user returns to your application the memory is gone, and you can't get that input you might need of your screen. Android framework is trying to make you serializing things in the bundles because if it decides to destroy your application you can always rebuild yourself from the bundle. Now there are short cuts you can take like redirecting people to start over if the Application has been reclaimed, but those depend upon your program and what its doing if they make sense.
That's where using serialization wins out over all other forms of persistence (parcelables, files, databases) because it can be done in one line of code.