Using cwac-endless adapter with existing/custom AsyncTasks - android

I'm currently using what I assume is a common pattern in Android, of fetching data from a network using various AsyncTasks, and updating a simple ArrayAdapter on completion using an interface callback mechanism.
cwac-endless is reasonably easy to plug in to add pagination type scrolling, aside from the fundamental issue that it assumes it will handle running the background task for you. Does this mean I basically have to rip up all my AsyncTask classes and associated interfaces, and move all the code from doInBackground into my EndlessAdapter's cacheInBackground?
Most solutions I've tried seem to end up duplicating much of the code already in cwac-endless, so I feel there must be cleaner solution to using this adapter with an existing AsyncTask?

cwac-endless is reasonably easy to plug in to add pagination type scrolling, aside from the fundamental issue that it assumes it will handle running the background task for you
Handling "running the background task for you" is most of the point behind the adapter.
Does this mean I basically have to rip up all my AsyncTask classes and associated interfaces, and move all the code from doInBackground into my EndlessAdapter's cacheInBackground?
If you wish to use EndlessAdapter as it stands, yes.
You are certainly welcome to grab the code, modify getView() to not use its own executeAsyncTask and AppendTask and replace that logic with your own. However, pretty much every line of code in AppendTask is necessary for EndlessAdapter to work. And I have no idea how any endless construct would work with "custom AsyncTasks" plural, as there has to be a clear end to the work so that we know to show the new rows in the list and get rid of the pending View. Hence, you would still need to designate some AsyncTask of yours as playing the role of AppendTask, doing everything that you are presently doing and all of the logic in AppendTask. Whether that is simpler than just using the existing EndlessAdapter code base, I cannot say, as I do not know your code.
I feel there must be cleaner solution to using this adapter with custom AsyncTasks?
You are the first person to ever raise the issue, and hence I have never considered it prior to typing in this answer. I will give it some thought and may try to do some refactoring to help with your scenario.

Related

Android: Separation of Rest API calling code, inside AsyncTask or separate?

I wondering if anyone can offer some suggestions on where I should be putting API Rest calling code. I of course could put this in every single AsyncTask that I am using. Which works but it doesn't make it very usable.
The other way I thought was creating an ApiConsumer class that would have all the rest calls list "getList()", "getExpiredItems()", "deleteItem(int id)" etc.
I though this would be ideal so they would be able to be used from everywhere. Inside these methods I am still using HttpUrlConnection to make network calls so I would still need an AsyncTask but instead of implementing the HttpUrlConnection stuff inside the AsyncTask then I would call the "ApiConsumer" methods that I setup before.
In my mind this seems a logical way of going, is it?
Am I trying to do something that has already has a different solution?
Anyone know of any articles or examples outlining similar solutions as I can't seem to find one.
I know placing HttpUrlConnection code directly inside the AsyncTask is ok, but I just don't see it very reusable and wanted to abstract it out.
Retrofit is something you should look at, it pretty easy to integrate, will save lots of development time.
Easy syntax,Support annotations
In built GSON deserializer
Customizable according to your needs
Content format Agnostic
Lots of devs are using it, so you will get good support over web
Volley & AsyncHttp are also good alternatives, you will find plenty of such libraries.
P.S: I am using retrofit for most of my projects

Ways of making async service calls in Android? and when to use which?

If I want to make a request from an Android device to a remote service, I can use AsyncTask, AsyncTaskLoader, Intent, etc to make the a request apart from the UI thread. It seems there are a lot of options, but I am confused how to choose among them. Could you explain when and which to use? Also, are there any other options besides the ones I have mentioned?
This is an extensively discussed question, since Android provides a long list of mechanisms capable to handle service calls asynchronously, besides the one you mentioned there's also:
IntentService
Native Threads
Now, the key point in your question is "When to use it" and here would be my answer:
In software the only golden rigid rule is the "It depends rule", there's no hard rules for anything in software development there's always different ways to approach a problem in software (i guess that's the reason of the word "soft" in it...) and that's exactly why it always depends, it depends on whatever you need and although one approach might be the most common way to do it like for example "AsyncTask" it doesn't mean at all that AsyncTaks is always the way to go, it always depends on the factors and needs that affect your functionality. There's plenty of things that nowdays get executed using AsyncTaks when maybe all you need could be just a regular common Native Thread.
The only way to be able to make a decision towards the most appropiate approach would be knowing ALL the features around a tool, like for example most people 90% of the time use AsyncTaks just to run doInbackGround on separate thread, but might not even need preExecute, publishProgress, postExecute, etc, and that's something a Regular Thread could do, just like this example there's features for every single object provided in order to do remote calls, however as i already mentioned several times, it all depends on what you need and what tool fits better your needs. Remember there's no hard coded rules for "How, When, and What" to use in software, IT ALL DEPENDS, and making good decisions in that "DEPENDS" makes the difference between good developers from excellent developers...
This is a list of things i usually take on count to implement either one way or another, this list do not apply for all the scenarios but might give you an idea.
AsyncTaks- I know is a good idea to make use of asynctaks when the functionality needs to be monitored, by monitored i mean, i need to keep track of progress during my job, like (download/task progress), because that's exactly what the AsyncTask was originally created for, it was created attached to "The Task Pattern", and if i don't need to make use of at least two methods for monitoring provided by AsyncTaks like onPreExecute,onProgressUpdate, onCancelled etc. I know there might be another way to implement it.
Native Java Threads - I know is good to make use of this tool when my task is not related to any view in android at all, and do not need to be monitored (example: removing/adding data from remote database, and the response might affect just persistence elements that will not be displayed like configuration preferences)
IntentService - When i want to do a one time task in a queueprocessor fashion way, but unliked a native thread, here i would like to have some application context in order to maybe bind an activity etc...
Regards!

Android AsyncTask vs. Threads for a specific case

I am working on an application that Looks similar to the Google Play App (swipe view with gridviews inside the fragments, in addition data in the gridview [image + text] is retrieved from a remote server).
My problem is with background tasks. I can’t decide what to use for retrieval of data from the internet. Mainly I am trying to decide whether to use AsyncTask or manual threading.
Of course it would be easier to implement AsyncTask, but after some research I noticed that many people find it limiting.
In my particular case, I want to download data from the internet as Json Objects, parse them and display the data in the gridview. The gridview would have up to 30 items, each item contains a thumbnail and 3 textviews. In Android documentation, they say that AsyncTask is suitable for short operations (few seconds at most). Would filling up to 30 items be considered as a short operation?
I want the data to be fetched concurrently. Also I want to support Android phones from API 8 and above. I read that for different APIs AsyncTask behaves differently (serially or concurrently)
My question is: Is it appropriate to use AsyncTask for my app? Or do I have to do everything manually? Is ThreadPoolExecutor a 3rd way to do this? Is it easier than manual threading?
Any advice would be appreciated, I can't move forward in the implementation without deciding on this issue.
Thanks in Advance!
My understanding is that the comment about using AsyncTasks only for short operations is aimed more at not expecting the same views to be available when a long operation finishes. For example, if a user leaves the app and comes back or the current activity goes away for some reason. Typical ways around this would be to use a Service and start up a plain old Thread there, then send some message telling the current Activity to refresh when the operation is done.
The download and processing of your data is likely to be the longest operation. So I'd use that as a basis for whether this is short or long. If you don't care about persisting data at all and don't mind restarting downloads if a user leaves and comes back, you can just use an AsyncTask with very little thought.
If you are using a GridView, you should only ever be populating enough views to for just over the number displayed on the screen at one time.
I'd say that AsyncTask is fine in your situation assuming it's a few kilobytes of data and not megabytes or hundreds of kilobytes. Megs of data, I'd say move to a Service with a Thread. Hundreds of k, is a toss up.
Also, take a look into Loaders... if you want to see an alternative that is better for this kind of loading.
When attending DroidCon in London last year, a presentation brought to my attention why using AsyncTasks for loading data from the network is unreliable.
This presentation was about the RoboSpice library.
The site also has a very nice infographic explaining why exactly AsyncTasks are unreliable and what RoboSpice does to amend these problems.
Disclaimer:
I am in no way affiliated with RoboSpice, nor have I ever tried it. I was just impressed and convinced by their presentation that it's a tool worth trying.
Friend, I am working in a project exactly as you need, and to support API 8 and above you should use Asynctask to download anything or you will get a crash for API 15 and above, because it won't even let you run your app without AsyncTask even for short operations.
So as I almost did everything that you need and it is working very well for API 9 above, you should use Asynctask, I´ve implemented SherlockActionbar, EndlessAdapter and ViewPager all with AsyncTask, so go on, if you need more help just ask again later.

Adaptors as inner classes of activities, or stand alone classes?

I'm looking to establish some "best practices" for Android, with regards to code reuse, ease of programming/understanding, performance and memory. So, you know, just good code all around.
It seems like a lot of the Android documentation and object design pushes you towards having lots of inner classes. AsyncTask likes to load data right into Views. Adaptors like to have access to the LayoutInflator.
From a code reuse viewpoint, it would be nice to build a few adaptors or AsyncTasks that solve your problems, and reuse them as needed. This means passing around your context though, which feels dirty and can lead to memory pitfalls if not done carefully. The other option is to bake all the AsyncTasks and Adaptors that an activity needs directly into the Activity. This makes it hard to reuse code, but you can see where things are going easily and since you're using the context directly it's harder to hold onto things forever.
I'm also concerned about writing code that will look familiar to programmers we might hire in the future.
What are the coding standards for Android? What is the "best design" for an application which needs to load nearly all of it's data from the web, have a UI that works on phones and tablets (with different activities in each), and be easy to work with and extend for years to come?
You should look at this on How to code in android.
And you can use inner class or make a seprate class according to your need. For example when all data is being loaded from web in json format i always use a seprate class with a static method which will return the jsonObject and then i can call this method anywhere in my app and extract data from it.
Also i use single inner class of asyncTask perfoming different task in my activity like seraching and loading data in listview, loading data on user prefrences change.and so on.
In custom adapter i always prefer different class for them. It'll really make easy to work with them.
Hope it will help.
I've asked this before, and this is the way I do it.
If I'm going to use the adapter many times, I place all of my adapters into a package called "com.myapp.adapters" As for the AsyncTask, I always use asynctasks as part of activities.
If you only have a short adapter that does a little bit of work in an activity, there's no need to create a separate class file for it. Just stick it into the activity.

What is the advantage of loaders over Asynctask in Android?

Are there any advantages of Loaders over Async task? Also, how to make loaders compatible for phones with Android froyo.
Edit:
The primary problem here is that I'm not using the native DB(SqlLite). Using the DB on development server. Obviously, I can't use CursorLoader any more. AsyncTaskLoader has no examples at all. If any, please do link.
Is it a better idea to load the data required onto the local DB and then query it using CursorLoader?
Yes, Loaders are more advantageous than AsyncTask as they take care of a lot of things that AsyncTask falls short of, miserably.
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.
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.
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.

Categories

Resources