I'm on the situation where I have to share variables between activities... but I have one doubt. Which is better: Parcelable object or set it on a custom Application object.
When something is just going to be used in next activity I just pass it as a Parcelable object, and when it is going to be used in more than one activity, I put it on Application context.
What do you think? Is it right? Which is better in performance?
Thanks!
I think your approach is completely valid.
If it is something like a user object that is accessed in every Activity store it in a custom Application object, but be sure to have a way to recreate the object if the application object gets destroyed while the app is in background.
If it is something like a path or a choice the user made that determines how the next activity works send it with the Intent.
There are also some classes that are not easy to put in an Intent. I have an ImageCache that is attached to the application class that allows to keep images like a user profil image in memory between activity changes without the need to decode the bitmap multiple times. If they are designed in a way that they don't fill up all available memory those are also a good fit for a custom app class.
I recommend sharing data between activies with extras. If it's a own class, it must implement Serializible.
If you are feeling lazy, go with Application's singleton pattern.
But, if you want to code smarter, go with Parcelable.
Related
The only way that I see is to use a static variable, but it's not okay as I want to keep the ability to start multiple Activites.
In my case, I want to keep a reference of Dagger 2 Component.
It will provide objects like Navigator. I can't just store it into Bundle.
For now, I can't use Retain MainFragment instead of MainActivity because of this bug.(I'm at 23 API level)
Is there any Retain Activity implementation?
Huh, well you have two built in solutions in android to fix this problem:
1) If the object is serializeable or parcelable you can override onSaveInstanceState() and read the value out in onCreate. Here are the google developer docs for the specifics on that.
2) If your object is not serializable you can instead override onRetainNonConfigurationInstance() and return that object. You can then get the object back in onCreate. Look at this SO post for how to use this approach (don't persist your activity though! persist the object.). The drawback of this is that you can only persist one object at a time.
I have a more in depth write up of these two approaches and third, declarative approach that you can roll. It relies on onRetainNonConfigurationInstance and allows you to use annotations to declare what variables in your activity should be persisted. check it out here. That said, I wouldn't recommend using this unless you have more than one non-serializeable/parcelable object to persist.
Edit: clarified point that you shouldn't persist your whole activity using onRetainNonConfigurationInstance().
May be its simple question, may be its repeated question, this question s not for upvote and all.
I just want to pass my object from one activity to second and second to third activity. I know there are a lot of ways using shared preferences, Intent bundle from one to another activity.
The reason I want to know that why I can't use an object globally for all my activities and if I can how it is possible?
Thanks
There is a handful of ways in which you can achieve this.
Using a bus/listener:
https://github.com/greenrobot/EventBus
https://square.github.io/otto/
Using the application class (ready the first answer carefully, there are caveats):
How to declare global variables in Android?
And using utility classes with static methods.
Also, if you are have more than one fragment running at the same time, you can create your own interfaces and implement them where you need to receive the information.
I am making an Android app using the Parse SDK. What I am struggling with is the flow of creating a post. Currently, in my main activity, a user selects the type of post (photo, video, etc.) takes a photo/video and goes to the next activity called NewActivity. In this activity, a user can review the photo/video and edit the privacy or place of the post. to change the privacy or place launches a new activity for each.
The main problem I'm having is retaining and passing this Post object between the activities.
My first (bad) solution was just to pass the data with the intent in a Bundle, but this soon got very messy as I really needed to pass a Post object between the activities. I switched from that solution to using a Singleton class called, DataHolder.
In each activity, I call DataHolder.getInstance() and when the create post button is clicked, I create a new Post object by executing: DataHolder.getInstance().setPost(new Post()). In the following activities, as the user enters more information about a post, I set the Post's properties.
This was all working well until I ran into this issue. When I would return to my app (presumably it had been killed) I would get a NullPointerException because the Post object was null. I was looking through the Android docs on passing data between activites/services and needed a little help.
Should I be using the Singleton class pattern here? What would be the most efficient and easiest way to pass this Post object between the activities? Should I use an application singleton? I would use Parcelable or Serializable, but the Postobject is a ParseObject so this is not an option. Should I avoid passing the data altogether by using Fragments for the privacy and place activities (though they have different screens and different action bars)? Should I use startActivityForResult for the privacy and place activities?
You should consider that the app could be killed at any moment for any reason and be prepared for this. You could use something like a session object to communicate between activities. You can save it / load it as often as needed so you will not run the risk of loosing data. If you cannot serialize the actual object (eg the ParseObject) you could serialize the parts needed in order to reconstruct it (ie save the image in a temp folder and load it on demand).
Suppose I have an activity MyMainActivity, let's say complex enough with a bunch of code.
From another activity, to access a public variable or a method I instanciate :
MyMainActivity ma = new MyMainActivity();
ma.editVariableMethod();
String example_variable = ma.public_examplevariable;
When I instanciate MyMainActivity ma, is it like creating the hole activity again and storing everything from MyMainActivity to memory, and that way it takes the same amount of memory it would take if I was starting MyMainActivity, or is it just a link which permits to edit variables from MyMainActivity?
You can't instantiate an Activity. The framework has to take care of it. If you want to use public methods either make them static OR get a reference to a valid instance of the activity object.
Edit:
As Squonk pointed out, depending on your use case, it might be a better idea to just extract the shared logic to another new class, at least until you know what you're doing. Giving "full access" to internal variables or even methods in an Activity might seem to work, but it's very likely NOT the right approach.
It is a bad practice to share memory-resident objects between objects in Android, no matter what the objects are. Android won't ensure that it will work. There are alternatives available for most use cases. In the particular case of "accessing a public variable" in another Activity, you can call startActivityForResult(), or ensure that your Activities store data they want to "share" in SharedPreferences, etc.
If you have two or more Activities that use the same method, you should first consider if the class needs to be abstracted into a separate object. Ideally, Activities should be frameworks that delegate to POJOs.
I have a similar issue with this one:
Android: Multiple activity instances launched by same intent. Bring one uniquely to foreground?
I need to create a stack of activities, all created by using the same class: it is a class defining a news list, only there needs to be multiple children activities that are also news lists, but from different categories. (I do need to have these activities in a stack)
The trouble is I need to change data on each of these activities after they are shown, but I can't find a way to access each one of these activities separately, since they are all using the same class, so if I used static methods, I would change the data on all these activities at the same time. Ideally, there could be a way to use references of each activity, so that I can access methods on each one separately, but I don't think there is a way of doing this.
I might as well pass parameter IDs when starting each activity, and instantiate objects at the same time, for each activity, and using these IDs later access the respective objects' methods...
Edit to clarify: Let me use an example to what I am trying to achieve. I have an A class and I am using this same class to instantiate multiple activities, in a stack. After the creation of these activities, I need to alter data, say, on one of these activities statically, so by calling A.alterData(); , but not when the activities are created, so there is no way of doing this by starting the activities with different data.. Since there are multiple instances of this class, if I do so, this will result on altering the data on all these activities, that are using the A class. Would I be able to somehow use objects and methods to these objects to alter data on different activities that are using the same class?
any other ideas?
You could use an ActivityGroup. It basically holds a list of activities and you need to control the navigation around them. It sounds like it suits your situation. There are many examples of them that can be found through google.
How I would approach changing the data on the other screens is by using shared preferences. You can store whatever data you need in there, and then (through your activity group) when you change screen, the data is refreshed. This is faster and a little more efficient than restarting the intent every time.
Another way is to change the data in the background without the user noticing. This can be done because an Activity group loads all of the Activity it holds and they are always there in the background, running, unless the developer states otherwise.
You could grab a a hold of the appropriate instance of the class you want to change the data on and then just change it.
Does any of this make sense?
I can elaborate more if needed.
I would supply the parameters to each activity, such as:
intent.putExtra("category", categoryId);
That way you aren't managing too much global state.
About changing the data - if you are talking about refreshing the data from its original source, then you should probably be doing this in the onResume() method of the Activity. Check out the Activity Lifecycle.
This has a few benefits:
you will have access to all of the context of that Activity
you won't have to do something nasty like access another Activity's data
you won't waste time refreshing data the user isn't looking at
Even if you have to make updates to the data, there are ways to make sure each Activity "minds its own business".