multiple asyntask - android

This is somewhat design specific question but I am looking for right advice.
In my app I have 6 pages A,B,C... each of which will download data from server and display it. In this case among below mentioned approaches which one will be good.
1.For each A,B,C write inner asynctask class
2.write separate asyntasks like asyntaskA,asyntskB etc for each of these activities
3. write a single asynctask and route request of each activity through a requestcontroller class which creates instance of asyctask by passing context,url parameters
If the second approach is taken, is it possible to run one Activity and another Activity in onpause state while its asynctask still running?

In each page, if you are doing the same kind of operation (As in this case, downloading data and displaying it), you need not write separate AsyncTask classes. Just create as much instances as you need and call the execute() method. AsyncTask class will handle this in thread safe way.
Second part of your question is bit unclear, but if you meant switching between activities, it is possible with multiple instances of a single AsyncTask. You'll need to save and restore the activity states.
If the operation you performing is time consuming, say more than few seconds, it's not safe using an AsyncTask. The better option will be a Service.

There's no problem with multiple AsyncTasks. In one of my apps I have a grid-view with images and there's an AsyncTask for every image loading and generating a thumbnail image. They all run in parallel quite nicely.

Related

Does AsyncTask really do things in background?

I used AsyncTask to get html files from server. But when an activity starts, screen becomes white few seconds and displays data when fully downloaded.
I wanted it to display activity's basic layout first(e.g. actionbar) and downloaded data later. So I used Thread and the problem solved.(basic layout is first shown and data later)
I've been knowing AsyncTask do things asynchronously but in my case it didn't.(In doInBackground, I only did network connection)
Does AsyncTask really do things in background?
Does AsyncTask really do things background?
Yes.
Note, though, that AsyncTask is serialized by default, meaning that if you fork multiple AsyncTask instances, they will share a single thread, and the second and subsequent tasks will be queued up waiting until the first task completes. You can avoid this via using executeOnExecutor(), instead of execute(), to run the tasks.
There are other ways of misusing AsyncTask (e.g., calling get()) as well.

How to avoid multiple asynctask in one activity

I have an android activity that needs to run six asynctask classes.
I created my activity and it works fine, but with those 6 classes my code is so hard to comprehend or edit.
Maybe its dump but i am new in android so what i need is to know how to simplify my code a bit: is there a possibility to make all async tasks in one class knowing that they have different functionalities
You can have one Async Task only and do different things in it by passing a functionality ID, if you may, as a parameter.
Although, I strongly recommend you to create 6 different files, each containing your Async Task class (if they have truly different functionality) and put them in a package "Async Tasks", if you may.
If, for instance, you need to do different sort of requests to a server, you should only have one Async Task, different parameters (such as URL, post parameters, etc) and handle the result different in your onPostExecute method according to the type of request you have done: send an event to your activity that calls the proper method to handle the result.
You can use this technique to manage you more-general Async Tasks
is there a possibility to make all async tasks in one class
Yes, but don't. You mention "simplifying" your code - putting more functionality into one class will make it difficult to understand what that class is responsible for.
The better option would be to add 6 different implementations of AsyncTask, and create new instances of them in your Activity. The names you use for the classes should represent what they do, and they should do as little as possible.
You could move your AsyncTasks to separate files. You could pass the Activity to your AsyncTasks constructors.
Might be you also could combine some of your tasks into one.

Using AsyncTask to preload data for a new Activity

I have my MainActivity which gives the user a selection of pages to open, all of which involve downloading some data from the internet and displaying it. To save the user waiting when they choose their page I've made an AsyncTask as a subclass of MainActivity which produces an object DATAwhen the download is complete.
How would I pass DATA on to the SecondActivity in the following circumstances:
The user chooses the SecondActivity before the AsyncTask download has completed.
The download completes before the user chooses the SecondActivity.
the AsyncTask doesn't have to be a sub-class of MainActivity its just been tidy to do it that way so far,
thanks for the help!
Here's one way to do this:
Create a reference to your data in your Application. The Android Application is a good place to store global data. Next, populate the data via your AsyncTask (Watch out for the pitfalls of using an AsyncTask). You can now access your data via a call similar to this: ((MyApplication)getApplication).mydata
As you mentioned, two scenarios can come up. Either the data has been populated, or not. To handle this, use an observer that observes changes to the data. Have SecondActivity register as an observer when the data is null. When the data is available your SecondActivity's update method will get called and you can do whatever you please with it. Finally, make sure to unregister from being an observer.
Hope this helps.
Passing information directly between activities works only if it is Parcellable (via Intent). Almost anything could be made Parcellable but it is not always a good idea especially when the amount of data is large.
The next problem is that your AsyncTask most likely keeps the Context of your first activity alive when it is running longer than the activity lasts. Activity instances are quite often recreated when you rotate the device and naive implementations tend to start another asynctask in the new instance and end up with multiple tasks that download the same data. You would need to pass the reference of a running task between instances of the same Activity.
The simplest solution is probably to create a singleton (or a Service) accessible from both activities that hosts the AsyncTask & loads the data. If it requires a Context use getApplicationContext() since that's safe to use outside the lifetime of Activites.
Activities could register themselves as listeners for "data loaded" events while they are active.
I've recently struggled with AsyncTask and had difficulty having the UI behave while the task was running in the background. While there are comments around that services aren't really appropriate for the sort of thing you're describing, I've found them much easier to work with. You might check intentService as a middle ground. Good tut's can be found here and, specifically concerning intentService, here.

Activity won't start until data is pulled from MySQL server

I have an Activity that displays a text based on data pulled from MySQL server. The problem is that the Activity won't load until data is pulled, which sometimes takes some long seconds or even doesn't load at all, and in the meantime the users gets a black screen.
I tried to pass the mission of getting the data from the server to a service, but also it waits for pulling the data and only then shows the layout of the Activity.
I also tried to make an activity with fixed text and then call the Activity that pulls the data from the server, but still the program wait for the data.
Can you think on a creative solution for it? or maybe a non-creative one as well :)
you can use asynctask for this:
http://developer.android.com/reference/android/os/AsyncTask.html
or you can show a waiting dialog to user until you get your data(do it in separate thread).....
or you can implement a splash screen and there you can fetch data.....
You need to do it inside another thread. Try using AsyncTask class.
The delay is probably due to the call to fetch the data being done on the main thread, also called the UI thread. Processes which take any significant amount of time, and by that I mean even a second or two should be done in a seperate thread. Android provides a class called AsyncTask to help make threading painless.
You mention you tried a service but did you take a look at an IntentService? (Can't link it yet but it's on d.android.com.) I like using them for these kind of tasks cause they handle the threading for you (like an AsyncTask) and it separates concerns better. The IntentService then sends a broadcast message that the activity picks up indicating that the data is available or not. Store the data locally in a sqlite db or as a json/xml file.

When should a (potentially) longer tasks take place?

I've got 2 tabs in my app, one grabs my contacts and geocodes their postcodes, the other tab plots them on a map.
The geocoding process can be quite time consuming. What is the best practice for handling such length processes?
Should I have a loading bar when the app starts and do all of the geocoding then or should I force users to click a button to do the geocoding?
You should move any operation that takes more than about 200ms onto a separate thread, so the app doesn't lock up, and then from that thread update an indicator to show the user progress.
You need to learn about the AsyncTask class, it's absolutely central to writing responsive Android apps.
http://developer.android.com/reference/android/os/AsyncTask.html
It's a pretty straightforward wrapper than makes threading easy. Remember to STOP threads when they're not needed any more, e.g. in onPause().
I tend to put AsyncTask subclasses into their own class file (not as an inner class) and pass them an activity context as a constructor parameter, so the AsyncTask thread always has easy access to the activity to update the user interface (but NOT from doInBackground).
Some limitations of AsyncTask
http://foo.jasonhudgins.com/2010/05/limitations-of-asynctask.html

Categories

Resources