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 SQLiteCursorto theListViewusing aCursorAdapter.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
LoaderManagerframework (available since Android 3.0/ API level 11, with Android support package down to 1.6/4) which will automagically do asynchronous loading of yourCursor— either using the built-inCursorLoader(if you happen to have aContentProvider), or theSimpleCursorLoadercreated by a fellow SO user (if you don’t).