Reputation: 12566
I have an application that will be accessing the web. I've decided to use Spring Android as the RestAPI, and with the help of a Thread
have got this simple demo working. My question is, how do I go about changing it to populating an actual ListView
rather than just logging the output of the object? Some other questions on here have led me to believe that AsyncTask
may be the answer, but I'm still a bit confused as to how I update the UI, as it is my understanding that other threads can't touch it.
Here is what I have now, minus the function that creates the RestTemplate, and makes the request, as I believe it is not relevant:
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
new Thread( new Runnable() {
public void run()
{
// create a RestTemplate. This is used to communicate with the server.
RestTemplate restTemplate = getRestTemplate();
String url = "http://192.168.2.14:8888/";
JSONData[] jsonData = restTemplate.getForObject( url, JSONData[].class );
for( JSONData d : jsonData )
{
Log.d( "TEST", d.getName() + " " + d.getId() );
}
}
} ).start();
setContentView( R.layout.main );
}
Upvotes: 1
Views: 674
Reputation: 137322
There are several options, listed in the very nice article (Android) Painless Threading.
AsyncTask
is one of the options and it seems to fit your needs, and there are several methods of it that run on the UI thread, such as onPreExecute
, onPostExecute
and onProgressUpdate
.
Upvotes: 2
Reputation: 157447
if want to change the UI from a different thread, you can use Handler or Activity.runOnUiThread().
Upvotes: 4