简体   繁体   English

如何从内部AsyncTask类的onPostExecute方法修改外部字段?

[英]How to modify external field from onPostExecute method of an inner AsyncTask class?

In the following snippet: 在以下代码段中:

public class ExternalClass {
    private int num = 1;

    public void backgroundTask() {
        new HttpTask().execute();
    }

    public int getNum() {
        return num;
    }

    private class HttpTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //Do stuff...
        }

        @Override
        protected void onPostExecute(String result) {
            //Do stuff...
            ExternalClass.this.num = 2;
    }
}

In an Activity: 在活动中:

...
ExternalClass ec = new ExternalClass();
ec.backgroundTask();
int myNum = ec.getNum(); //NUM IS 1, NOT 2!!

What am I doing wrong? 我究竟做错了什么? Everything works fine, my doInBackground() and onPostExecute() complete successfully but the field "num" don't change. 一切正常,我的doInBackground()和onPostExecute()成功完成,但字段“ num”没有改变。 I tried "num = 2" or even "this.num = 2" (I know is no correct, but...). 我尝试了“ num = 2”,甚至“ this.num = 2”(我知道这是不正确的,但是...)。

you will need to use AsyncTask.get() method to get result back in Main UI Thread from AsyncTask when doInBackground() execution complete doInBackground()执行完成时,您将需要使用AsyncTask.get()方法从AsyncTask返回主UI线程中的结果

public void backgroundTask() {
        new HttpTask().execute().get();
    }

NOTE: when u call get() method of AsyncTask in Main UI thread this will stop exection of Main Thread . 注意:当您在Main UI线程中调用AsyncTask的get()方法时,这将停止执行Main Thread。 you will need to call backgroundTask() method from background Thread 您将需要从后台线程调用backgroundTask()方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM