Calling AsyncTask from AsyncTask - android

Although I have not tried it yet, but from theoretical point of view I'm asking this question just to clear my doubts.
I have a scenario like:
1. Send a request to a server and receive JSON response. For this I'm using AsyncTask as there can be delay in receiving response.
2. From this response fetch an image URL.
3. Using one more AsyncTask, call the image URL and fetch the image. (Again may take time to fetch image)
So do you think using of 2 AyncTask just to get that image is inefficient.
OR, in step 1, instead of using AsyncTask, run the code sequentially and set Timeout instead.
Please suggest.

I'm going to go ahead and suggest this as an answer, which was originally in my comment:
Just fetch the image synchronously in the same AsyncTask that you're fetching the JSON from. For example:
doInBackground(Void...params){
//fetch JSON
// once JSON is fetched, fetch image
}

Not sure how you want to structure this exactly, but documentation says:
execute(Params...) must be invoked on the UI thread.
http://developer.android.com/reference/android/os/AsyncTask.html
so you cannot execute new async task from other async task background method.
even if you tried doing this from progress method, then since HONEYCOMB asynctasks are serialized, so your second async task will get queued anyway - you would have to use THREAD_POOL_EXECUTOR to make it run parallel.

Related

Network request using asyntask and method order

I have a little app that is doing something like the following
inflating the layout
getting viewpager from layout
getting json object from network using asyntask without .get() to avoid blocking UI
setting viewpager adapter that requires the json object from network and using data from json
Returning layout
The issue here is that if using asyntask without .get() in some case I get null object and app crashes, most likely due to no json object present yet. I should somehow have the user wait there, and I do use splash screen on pre-execute and hiding on completion of asyntask, but the order there can't be changed, since it's within the viewpager adapter setup. So the execution of the code does not stops there.
With these case, what is the best or proper approach. It seems to me that I can't avoid the UI blocking. Has anyone else had a similar case?
Some pointers would really be great :(
Thank you.
There is no need in calling AsyncTask.get(). I guess you are misusing AsyncTask. It only returns that what you are returning in your doInBackground() implementation, and here you are returning null somehow.
Blocking UI is definetly no option! Forget it!
I would recommend to use well known http libraries like retrofit
or Volley

Parsing two (or more) JSON requests to a single ListView [Android]

I am trying to parse two (or more) JSON requests to a single ListView. Is that even possible?
Now, im using JsonArrayRequest along with the RequestQueue.add().
And it works perfectly, the only issue is - when I try to add another JSON request to the request queue it mixes them up in the ListView - sometimes the second request is above the first one and vice versa. It should be a Section Header, followed by the First Request, then another Section Header, and then the Second Request. Both the requests are from the same table just different WHERE parameters.
I really could not identify any logical pattern so I'm assuming it is done randomly. How or why is that happening?
You're probably adding to the ListView from two separate Threads.
You have two options, Either wait for the first Thread to finish then run the second one. (in onPostExecute() of the AsyncTask).
OR
you can run both Threads but only call adapter.notifyDataSetChanged() after the execution of whichever runs last thread. you can use a boolean to indicate which thread runs last.

Check if there is errors after some asynctask

I have 2 main AsyncTask which goal is to syncronize my app.
uploadFile and SyncData
So, if I have 3 pic to upload, I will have 3+1 = 4 threads
Each process fill a global error variable.
So what I need is to get a way to run this method after all threads are done.
How can I do it???
for (Captura capt : lCapturassASync) {
uploadFile(capt, ctx); // Is also an AsyncTask
}
new SyncData(ctx, lTiendasASync, lCapturassASync).execute("upload_datos", null);
Basically what you want to do is know when the async tasks were done in other threads.
About doing it on java specifically you can read this it might give you a very good idea on how:
How to know if other threads have finished?

Best practice to use AsyncTask in autocomplete?

I am using Async task to populate auto-complete suggestions from server.
Problem:
when user types and removes the text in edittext so many times.
lets say he typed: cofee > cof > coffee >coffee late .... etc for so many times.
for each text changed after 3 keyword(threshold) i am initializing an asynctask and ask for result.
so in current scenario i have so many threads running in background. so some of my latest async threads are waiting for there chance.
Whole this make my app very slow.
What can I do to tackle this problem?
If it is possible to load entire data from server at beginning...then you can avoid calling asynctask repeatedly and fetching the data from server. This will improve performance of you app. If data displayed in Listview is String, following link show how to filter it:
http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/
And if custom object is used in ListView adapter, try:
Filtering ListView with custom (object) adapter
Hopefully this helps.
You should cancel the current task before issuing a new one. Use AsyncTask#cancel(true) for that and make sure that the execution of the task can be quickly stopped. This means correct handling of interruption and frequent checking whether the task was cancelled in the body of AsyncTask#doInBackground.
And you cannot execute again the AsyncTask you have cancelled. You have to create a new one. (Trying to execute it again leads to IllegalStateExceptions)
It worked for me by cancelling the task each time you change the text (if it is still running).
You need to define your request once outside the listener(private for the class), and then start your listener function by (if your request is not finished, then cancel it).
define your request out side the function
private YourSearchTaskClass YourTaskReq = new YourSearchTaskClass();
then start your addTextChangeListener/afterTextChanged by this
if (YourTaskReq.getStatus()!= AsyncTask.Status.FINISHED)
YourTaskAvReq.cancel(false);
YourTaskReq= new YourSearchTaskClass(keyword);

Call more than 1 url simultaneously in Android through Asynctask?

I want to call more than one url and get the response from that with AsyncTask. Currently what happens is that I pass one url to AysncTask and then get the response of that and after that call another url. What I want to have is to pass all the urls at a time since doInBackground does take an array as argument. Once all the 3 urls are called get the response of each one of them.
You could create threads inside doInBackground and then call the join method on each one of them. You'd probably be better served by a thread pool though.
I was able to do that passing array of url in doInBackground and setting the return type for results as String[]. That gave me the response of each url called in string array in postExecute.
Anyways, Thanks for taking the time out and replying to the posts.
You can create multiple AsyncTask objects and execute them in parallel - assuming all URLs just have to fetch data.

Categories

Resources