sreekumar sreekumar - 3 months ago 10x
Android Question

What is the best way for fetching data and for passing to another Activity?

Most the app so far I had created, I fetch the data from Network and store it in a singleton class to share data between Activities, when I'm done with those data, I usually clear those setting it to NULL, its work perfectly well

My Question is which approach is better ??

  1. Use parcelable

  2. Writing in database and Query for it

  3. Singleton classes

When exactly we need to use Loaders ?? Why we can't share the data through Loaders ??

If question is repeated ... Please ignore ??


Answer to first part

  1. Parcelable:

    The best way to pass data between Activitys or Fragments is by using Parcelable objects. It is said to be more optimised than Serializable. There are couple of libraries/plugins which can help you create Parcelable objects. Lately I was referred to Parceler, created by John Carl. However, I personally use Android Parcelable code generator by Michal Charmas, plugin for IntelliJ IDEA and Android Studio.

  2. DataBase or SharedPreferences:

    Using DataBase or SharedPreferences to pass data between Activitys or Fragments sounds weird, and since they are not designed to be used this way, it will only create a mess.

  3. Singletons:

    Read this very informative post Singletons are Pathological Liars.


I recommend Parcelable or if you want to be real lazy then go for Serializable (it's not terrible but it's not great either, according to most).

Don't mess up your code by using singletons, DataBases, static fields, etc. They will come back and haunt you.

Answer to second part:

When exactly we need to use Loaders

Loaders, which will be AsyncTaskLoader when you use, are basically used for situations where we want to retrieve data from the server (via web API), or doing something in background. It is similar to using Thread or AsyncTask but is very powerful as it isn't destroyed on screen rotation, unlike those two.

You should read How to Use Loaders in Android and Alex Lockwood's posts on Loaders (this is a series of 4 posts. Very detailed and great).