I've seen many examples of how to do this, but I can't figure how to implement it in my code.
I am using this code.
I have updated the url, so it will receive a json with dynamic data.
What I'm trying to do is to automatically update the list every 30 secs with this code.
Handler handler = new Handler();
Runnable refresh = new Runnable() {
public void run() {
new GetContacts().execute();
handler.postDelayed(refresh, 30000);
}
};
It refreshes, and calls the url and gets the data, but the UI does not get updated.
Thanks for any hints to point me in the right direction.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });
Android Thread Updating the UI from a Background Thread The solution is to use the runOnUiThread() method, as it allows you to initiate code execution on the UI thread from a background Thread.
Alternative 1: Using Executor and Handler The executor will help in performing any task in the background and the handler will help to make UI changes.
The AsyncTask API is deprecated in Android 11.
You have three protected methods in an AsyncTask that can interact with the UI.
onPreExecute()
doInBackground()
onPostExecute()
doInBackground()
completesonProgressUpdate()
doInBackground()
calls it with publishProgress()
If in your case the Task runs for a lot longer than the 30 seconds you want to refresh you would want to make use of onProgressUpdate()
and publishProgress()
. Otherwise onPostExecute()
should do the trick.
See the official documentation for how to implement it.
You can use AsycTask
and update list ui
on task finished within onPostExecute
.
new AsyncTask<String, String, String>() {
/**
* Before starting background do some work.
* */
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
// TODO fetch url data do bg process.
return null;
}
/**
* Update list ui after process finished.
*/
protected void onPostExecute(String result) {
// NO NEED to use activity.runOnUiThread(), code execute here under UI thread.
// Updating parsed JSON data into ListView
final List data = new Gson().fromJson(result);
// updating listview
((ListActivity) activity).updateUI(data);
}
};
}
Update
No need to use runOnUiThread
inside onPostExecute
, Because it's already called on and it's body executed under UIThread
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With