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.
Related
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.
I need to fetch list of data from server, feed to adapter, and show in list view.
Question is who should do the backend call, activity or adapter or ?
And please elaborate why. This question is more about why than how.
Please answer in an model view controller or similar (I know strictly speaking android does not have MVC) context.
Edit:
It's now obvious to me adapter is very bad place to fetch data (imagine how un-flexible it will be. E.g., what if there are two end points for similar kind of data. Or I have two adapter for same data set, it make no sense to let one of the adapters fetch data). Other component should be fetching data and filling adapter. Activity is a good component to do so.
The accepted answer provides an illustration of doing it.
Never fetch data from an Activity because it will block the UI.
You should extend AsyncTask with parameters and return type as you wish.
Do your work on the method doInBackground (#Override it) and on the method onPostExecute (#Override it), call some public method on your Activity to give to it the data you fetched.
Finally, the Activity with the fresh data should feed it to do Adapter.
This is how I always get my data and I get the results 100% as I want (add a progressBar and make it visible before fetching the data and make it invisible after you give it to the adapter).
Hope I was clear enough to you. If you want some code as an example, please ask.
Workflow:
1 - Activity -> new MyAsyncTask(...).execute(); //get the data #Override doInBackGround
2 - MyAsyncTask.onPostExecute() {myActivity.giveFreshData(...)} //deliver the data
3 - Activity.giveFreshData(...) {MyListAdapter.giveMyData(...)}
Altough it isn't MVC this is how you should separate the UI from the data consumption and the data representation.
Neither of them, I would create a class that make the requests and transfom it into objects, then the activity take this objects and pass them to the adapter.
Actually you can fetch data directly from an activity, only if this is an async task. (but it would generate duplicated code)
The Adapter class it is usually used to transform objects into something visible in lists and stuff like that
The activity would be like a controller, that interacts with the class that fetch data from the server and the adapter.
then you will need a class to fetch the data and return it into java objects (is it not necessary, but if you are using MVC it is the ost correct way to do it). Also if you call directly an asynctask from the activity, if exists more activities that need to do this same request, then you will have duplicated code (and everybody know that it is never good). Then it is that why we need another class that will transform requests into objects in a callback captured by the activity, this class can be reused from all activities or classes.
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.
I need to display the names from SOAP web services, when I was singin my application next page spinner and some textviews. I'm getting response about text fields.
But I need to know how to get data into the spinner?
Basically you what you need to.
First you need to send a HTTP request to your server.And you better do via AsyncTask without interrupting your UI thread.
Secondly you need to parse the response from your request according to your needs.The response from web service can be either XML or JSON or something else.
And the last one you need to write your custom adapter to populate your spinner and then set it as your spinner adapter.
Get it into an array from the webservice in an async task and then populate the spinner from that.
I'm having issues with multithreading in my application. I know there are many posts on Threads/AsyncTasks/etc, but none seem to address my specific problem.
Basically, I get a query string in my search Activity, then send it to my results Activity, where the string is used as a SQL query, the results are returned as an array of JSON objects, then I display these objects in a ListView (which is part of the results Activity). All of my SQL connection and retrieval is done in a separate class that I call at the start of the results Activity.
MySQLRetrieve data = new MySQLRetrieve();
ArrayList<Tile> tiles = data.getResults(nameValuePairs, isLocationSearch);
The above code is how I get the SQL response and convert into an ArrayList, which I then use the populate my ListView with. getResults() takes care of all of this.
I already have separate threads working to download images into the ListView, but what I can't get to work is getting the SQL query and result to run in it's own Thread. What I want to achieve is this:
User enters search query in search Activity.
Intent is sent to results Activity, and it starts immediately.
ProgressDialog (just the animated spinner thing, not a loading bar) displays while the SQL query is taking place.
ListView populates with objects from the JSON array, lazy loading images as they come.
I have steps 1,2, and 4 working well, but 3 is the problem. I've looked up AsyncTasks, which seem to be the answer, but I just can't get them to work. Does anyone have a solution to this problem? I need to do this, so when starting the results Activity, the UI changes immediately to the results Activity and doesn't have to wait until the SQL response is returned.
And yes, I've already read the painless-threading post.
Thank you.
I would recommend against creating that ArrayList<Tile> to reduce memory consumption (and code size) and instead directly bind the SQLite Cursor to the ListView using a CursorAdapter.
That alone might just increase the performance enough that you don't need to do any async loading.
If you still want async loading, check out the LoaderManager framework (available since Android 3.0/ API level 11, with Android support package down to 1.6/4) which will automagically do asynchronous loading of your Cursor -- either using the built-in CursorLoader (if you happen to have a ContentProvider), or the SimpleCursorLoader created by a fellow SO user (if you don't).