0

I don't like the intent way of passing data between activity. This result in more duplicate code.Passing data from activity A->B and from B->C and in some cases C->D makes code more error prone. I want to pass both primitive and non-primitive data type. How to achieve those without compromising on code Quality?

Community
  • 1
  • 1
Madhav Bhattarai
  • 847
  • 2
  • 10
  • 29

2 Answers2

1

If it's simple data you can use SharedPreferences to store the data in one activity and read it in another activity.

Other options are to store the data in the Application class , but this should only be a cached copy of what you store in shared preferences, since the application object can be killed at some point.

What I do is have a single object a singleton instance of a PersistData class which handles saving and loading (and caching in the Application class).

I use Dagger to inject this object were ever I need the save/read the data.

Here is a link to another answer I made to a related question that does a better job of explaining what I am proposing (sorry I was spending some time searching for this)

best practice to share global variables between activities

In the end you just have two calls to make:

In the activity that has the data you want to send, you have something like

persistData.saveUserId(userId);

In the activity you want to receive the data you have something like this:

String userId = persistData.readUserId();
Community
  • 1
  • 1
nPn
  • 16,254
  • 9
  • 35
  • 58
  • SharedPreferences uses pair concept. We need to check for !null or empty string every time when we need to read the value, which results in a lot of duplicate code. – Madhav Bhattarai Dec 11 '14 at 03:17
0

You can use a singleton class to store objects and retrieve them in other activity by getting instance of that singleton class.

Ref: http://developer.android.com/guide/faq/framework.html#3

Madhav Bhattarai
  • 847
  • 2
  • 10
  • 29
Tushar
  • 481
  • 6
  • 26
  • 1
    Just read this before you settle on the singleton in the application object. It might work fine for you but , just be aware of the possible issues. http://www.developerphil.com/dont-store-data-in-the-application-object/ – nPn Dec 11 '14 at 03:54