AsyncTask “Only the original thread that created a view hierarchy can touch its views.”

后端 未结 4 2020
情歌与酒
情歌与酒 2021-02-20 10:50

I try to modify the Spinner content across the AsyncTaks but I can\'t and the Logcat is wrote \"09-19 16:36:11.189: ERROR/ERROR THE(6078): Only the original thread that created

4条回答
  •  臣服心动
    2021-02-20 11:11

    If you want to show the progress during the background process, none of the previous answers give an hint: When OnPostExecute is called everything is finished so there's no need to updated status of the loading.

    So, you have to override onProgressUpdate in your AsyncTask and be sure that the second object is not a Void but an Integer or a String that is read by onProgressUpdate. For example using String:

    public class MyAsyncTask extends AsyncTask {
    
        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            if (values != null && values.length > 0) {
                //Your View attribute object in the activity
                // already initialized in the onCreate!
                mStatusMessageView.setText(values[0]);
            }
        }
    }
    

    Than in the background method you call publishProgress(value as String) which automatically calls onProgressUpdate method which use main UI thread:

    @Override
    protected Boolean doInBackground(Void... params) {
        your code...
        publishProgress("My % status...");
        your code...
        publishProgress("Done!");
    }
    

    More in general, when you declare an AsyncTask you have to specify the classes that are passed to the main methods, these can be your own classes or just Java classes:

    • doInBackground(Params... params)
    • onProgressUpdate(Progress... value)
    • onPostExecute(Result... success)

提交回复
热议问题