Rafe
Rafe

Reputation: 809

Sharing state across Android activities

I'm having trouble passing along state data between different activities. Right now I have four of them:

First I stored the state of this workflow in the instance variables of activity A, but most of the time Android had garbage collected A when returning from B (probably because of orientation changes) so I was getting Null Pointer Exceptions. Then I tried storing state inside a parcelable object, which was created when B returned to A with a result, and then passing along that object to C. It arrives at C fine, but when I'm parceling the object again from C to return to A it doesn't arrive for some reason. This results in another NPE when trying to hand the object from A to D.

In the end, the data needs to be deleted: either by D after uploading or if you close the app halfway and don't complete all the activities. You would start over again at A (or B, which is an actual usable activity).

By now my current structure is feeling way more complex then it should be. I think activity A should be cut out. But I'm unsure on what to implement in its place. Also I'm unsure on how to make activity C repeatable for 2 or 3 times, with each time adding data, before going to D. Possible solutions I've found:

I'm new to Android development... I'll probably could get all of them working sooner or later, but what is the proper solution for my case?

Upvotes: 1

Views: 1671

Answers (2)

Rakesh Bhalani
Rakesh Bhalani

Reputation: 678

You can use

android.app.Application class

In your app, it is application level class and it is created automatically by configuring it in menifest.xml file. You can access this class in activity by

getApplication();

You can set application level data in this class and from one activity and use it in another activity

Upvotes: 1

Andrey Novikov
Andrey Novikov

Reputation: 5593

You should pay more attention to Activity Lifecycle. In your case it would be enough to use extras in your intents and results. Services and SharedPreferences are definitely not what you want. Extending Application is a good option in case of very complex or huge data, but this does not look like your case.

Upvotes: 2

Related Questions