What is the advantage of loaders over Asynctask in Android?

萝らか妹 提交于 2019-12-04 02:52:11

Yes, Loaders are more advantageous than AsyncTask as they take care of a lot of things that AsyncTask falls short of, miserably.

  1. Screen Orientation changes are difficult in AsyncTask. I used to have such a problem, till I used an Activity Control class, which I used to retain while configuration changed. I can give you some code if you want to know how. The app used to crash, though, when you changed the orientation multiples times even before the entire data loaded. The secret here is not load a lot of data with your first thread and and finish your threading tasks as soon as possible. Even if it happens in the background, Android has a shabby way of dealing with threads. You never know when one of your tasks would be killed.

  2. Even if you use a AsyncTaskLoader, makes sure that you use an Activity manager. This will help you in getting more control over the activites and AsyncTask.

Yes, it is compatible in all the old version of Android. You need to include the support library(Most of the times, this is included by default but its always nice to double check.)

For one, loaders are easier to code (they're almost built-in in Fragments). Loaders (specifically CursorLoader) also handles your cursor for you (like the deprecated manageQuery).

Check out this link to read on how to use Loaders pre-Honeycomb.

Kingamajick

There simpler to implement and take care of a lot of the life cycle management which previously had to be done "by hand" with AsyncTasks. See the answer to this question for further detail.

With regards to using them with Froyo, they're available via the compatibility library.

It seems no one is talking about the disadvantages of loaders! I'm currently working on a system that runs other services in the background.

What I have noticed is that as soon as a screen with a loader is resumed. The cursor used by the loader locks up the DB.

It may not be open to most people but getDatabaseWriter from sqlite is actually a synchronized method and hence the cursor used by the loader is never closed until the loader is reset or terminated thus locking up access to the DB.

I cannot recommend using a loader under these circumstances nor can I advice using a loader when your result set consists of less than 100 items which are static and never seem to change.

Another advantage with loaders is that they handle screen turn event gracefully whereas asynctask can give you trouble.

Biggest diff:

CursorLoader will update your UI's content as soon as its related ContentProvider changes its content(say through a Service), while AsyncTask will only update your UI when you tell it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!