I've made an application that Fetches a Webpage from the internet, based on user input, wich worked. The fetching goes in different steps: post with String from edittext as parameter, after some parsing this returns an Array of names wich are displayed in an AlertDialog. When the user picks one, it makes another post with that String as parameter.
This works, but now I want to make it Threaded (or similar), so that the UI doesn't get unresponsive.
I tried Threads, Runnables and AsyncTask, but I just cannot find out a construction to get the fetching in a single Thread, and also be able to return that array and pick a name, WITHOUT making a new instance of my HttpClient. This would erase Cookies you see...
I've spent about a whole week to figuring this out, but just don't see it :(
So anyone got an idea? thanks !
For each of your HTTP accesses, you can create a separate AsyncTask subclass, then instantiate each one of them in turn, and execute them. On the web there are many examples on how to use AsyncTask to access HTTP, e.g. here or here (just google for something like this).
The main idea to grasp there, is to do all the network-related operations inside the doInBackground method body of the AsyncTask.
As Ted Hopp said, you can let the HttpClient instance be a private member of your Activity (or whatever class holds the two AsyncTasks), so that the first AsyncTask will create it, and the second one can just use the same.
You can use two AsyncTask subclasses, one for each request. Give the subclasses access to a variable in your activity class that stores the HttpClient object.
Related
I have an app underdevelopment and I need to do 3 HTTP POSTs in sequence. What is the best way to implement this ? Should I
Make each HTTP Post in it own Async Class and daisy chain the Async classes(i.e. call the second async from the onPostExecute of the first Async)
Put all the HTTP POSTs in the doInBcakGround of a single Async.
I know how to do a HTTP POST request and I am using the OKHTTP lib. I just would like to know that the best practice it for multiple POSTs in sequence.
Cheers
Your first approach will be better and quite modular as you can keep the track of anything in your application.In the three different AsyncTask you can have a check in postExceute() that which AsyncTask is done with its work (more easily and precisely) AND
>>>>>In case if the application gets Crashed
then which of the httpPost failed. However , the second one will make your code messy and you will be unable to track on getting Exception that which httpPost request failed(in a straight forward way though).
So Launching your second AsyncTask from onPostExecute of your first task will be better approach.
See here too : Calling an AsyncTask from another AsyncTask
Both 1 and 2 approaches make app ANR, so better to for other approach.
You can use ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
here is more deatias
http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html
Put all the HTTP POSTs in the doInBcakGround of a single Async.
because all your posts handle in one module.
dose not have overhead of creating asyntask and GC may not call as many as your first.
you do not need to check internet connection 3 times you have to check it one time
all exception handles one time but in approach 1 you have to copy and paste all exception handler that may occurs. and always recommended not to repeat yourself. if you can do something to not copy and paste codes, do it.
At the end I prefer approach 2.
I am writing an app that accesses a web site, downloads XML responses and acts on the response.
I have used the solution discussed at How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?, but due to the limitation of AsyncTask only being able to run once, I cannot reuse the AsyncTask for reading the next XML response required. Is AsyncTask the solution for me, or should I be writing my own threaded activity?
There's three ways to do it.
1)Create a new AsyncTask in onPostExecute to do the next task.
2)Create multiple AsyncTasks at the beginning if you already know you'll need another
3)If you know you're going to be reading xml all the time, then a Thread rather than AsyncTask is appropriate.
So I have an app that will make multipe HTTP Post/Gets
E.G. Login, getThisData, getThatData, sendThis, sendThat
Is it better to have a seperate AsyncTask to handle each one
Or one async task and process them differently with a switch in onPostExecute and doInBackground
Cheers
Short answer is yes you should create a new AsncTask for each call.
And if you interested, the long answer is;
According to the Android's Asynctask documentation,
The goal of the AsyncTask is to take care of thread management for you and you should not worry about the threading mechanisms.
The Android Platform handles the pool of threads to manage the asynchronous operations. AsyncTasks are like consumables. The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Happy asynchronous coding! :-)
It depends on whether the tasks are independent on each other or whether they are interrelated. If independent you can handle this through the same async. For ex if you need some data from your login response and pass that value to getthis task you better use separate async.
Make login a separate async, getthis ,get lthat sendthis sendthat can be in one async.
You'll probably want to separate them, especially if their functionality in the pre/post executes differs. Try to organize your code into logical blocks. For example, if you have an Async Task to Login, and an Async task to, for example, download lots of document data via JSON, they will want separate Async tasks.
However, lets say you have two separate API calls that return similar or partially the same data - if one returned the details of a file (name, size) and the other returned the same data but was a revision of a file - you could switch these in the same ASYNC because the post execute is going to perform the same (or partially the same) code to extract data from the JSON.
If you want to create one instance of AsyncTask, and execute() it several times, no:
Execute AsyncTask several times
If you are asking about designing: whether you should write one class to get different kind of data? It really depends on your circumstances:
If these HTTP call supposed to be sequential, you can put them in one AsyncTask class.
If they have lot in common, just point to different URIs, you can write a call(String uri) method, and invoke that method in your AsyncTask. This case, I think one AsyncTask is also enough.
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.
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.