How To Update Ui From Background Task
My app is not working on android version 4.1 gives exception like android.os.NetworkOnMainThreadException i have search on stackoverflow advice me to do network thread in backgroun
Solution 1:
Use the Handler object from your MainActivity and post a runnable. To use it from the backgrund you need to make the object a static that you can call outside of your MainActivity or you can create a static instance of the Activity to access it.
Inside the Activity
privatestatic Handler handler;
handler = new Handler();
handler().post(new Runnable() {
publicvoidrun() {
//ui stuff here :)
}
});
publicstatic Handler getHandler() {
return handler;
}
Outside the Activity
MainActivity.getHandler().post(new Runnable() {
publicvoidrun() {
//ui stuff here :)
}
});
Solution 2:
You can use **runOnUiThread()**
like this:
try {
// code runs in a thread
runOnUiThread(newRunnable() {
@Overridepublicvoidrun() {
// YOUR CODE
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
Solution 3:
You need to create AsyncTask class and use it Read here more: AsyncTask
Example would look like this:
privateclassUploadTaskextendsAsyncTask<Void, Void, Void>
{
privateStringin;
publicUploadTask(String input)
{
this.in = input;
}
@OverrideprotectedvoidonPreExecute()
{
//start showing progress here
}
@OverrideprotectedVoiddoInBackground(Void... params)
{
//do your workreturnnull;
}
@OverrideprotectedvoidonPostExecute(Void result)
{
//stop showing progress here
}
}
And start task like this:
UploadTask ut= new UploadTask(input); ut.execute();
Solution 4:
you are handling ui in these methods
public View createRow(JSONObject item)throws JSONException {
Viewrow= getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item)throws JSONException {
Viewrow2= getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
which are called in background thread
if possible do it in onPostExecute or you can use runOnUiThread and Handler.
Post a Comment for "How To Update Ui From Background Task"