how to update Ui from background task

若如初见. 提交于 2019-12-02 09:47:36

You can use **runOnUiThread()** like this:

try {
   // code runs in a thread
   runOnUiThread(new Runnable() {
       @Override
       public void run() {

         // YOUR CODE

       }
  });
} catch (final Exception ex) {
     Log.i("---","Exception in thread");
}

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

    private static Handler handler;


    handler = new Handler();

    handler().post(new Runnable() {

        public void run() {
            //ui stuff here :)
        }
    });

    public static Handler getHandler() {
       return handler;
    }

Outside the Activity

    MainActivity.getHandler().post(new Runnable() {

            public void run() {
                //ui stuff here :)
            }
        });

You need to create AsyncTask class and use it Read here more: AsyncTask

Example would look like this:

private class UploadTask extends AsyncTask<Void, Void, Void>
{
    private String in;

    public UploadTask(String input)
    {
        this.in = input;
    }

    @Override
    protected void onPreExecute()
    {
        //start showing progress here
    }

    @Override
    protected Void doInBackground(Void... params)
    {
      //do your work
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        //stop showing progress here
    }

}

And start task like this:

UploadTask ut= new UploadTask(input); ut.execute();

you are handling ui in these methods

public View createRow(JSONObject item) throws JSONException {
    View row = 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 {

    View row2 = 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!