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 ??
When exactly we need to use Loaders ?? Why we can't share the data through Loaders ??
If question is repeated ... Please ignore ??
Parcelable:
The best way to pass data between Activity
s or Fragment
s 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.
DataBase or SharedPreferences:
Using DataBase or SharedPreferences
to pass data between Activity
s or Fragment
s sounds weird, and since they are not designed to be used this way, it will only create a mess.
Singletons:
Read this very informative post Singletons are Pathological Liars.
Conclusion:
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.
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).