异步内部的Android SetText对UI没有影响



我有一个与 AsyncTask相关的问题。我想更改onPostExecute方法中的文本,但它不起作用。我真的不知道我在做什么错。有人可以帮我吗?

我不明白当我将AsyncTask称为嵌套类时,为什么它会起作用,但是当我将其声明为自己的类时,它不起作用。

这是我的代码:

mainActivity.java

public class MainActivity extends AppCompatActivity {
    private Button button = null;
    private Helper helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.helper = new Helper(this, getLayoutInflater());

        this.button = (Button) findViewById(R.id.button1);
        this.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    new MyAsyncTask(helper).execute("");
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

helper.java

public class Helper {
    private Context context;
    private LayoutInflater inflater;
    public Helper(Context context, LayoutInflater inflater) {
        setContext(context);
        setInflater(inflater);
    }
    public Context getContext() {
        return context;
    }
    public void setContext(Context context) {
        this.context = context;
    }
    public LayoutInflater getInflater() {
        return inflater;
    }
    public void setInflater(LayoutInflater inflater) {
        this.inflater = inflater;
    }
}

myasynctask.java

public class MyAsyncTask extends AsyncTask<String, String, String> {
    private Helper helper;
    public MyAsyncTask(Helper helper) {
        setHelper(helper);
    }
    public String getJSON(String url, int timeout) {
        HttpURLConnection c = null;
        try {
            URL u = new URL(url);
            c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setRequestProperty("Content-length", "0");
            c.setUseCaches(false);
            c.setAllowUserInteraction(false);
            c.setConnectTimeout(timeout);
            c.setReadTimeout(timeout);
            c.connect();
            int status = c.getResponseCode();
            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "n");
                    }
                    br.close();
                    return sb.toString();
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (c != null) {
                try {
                    c.disconnect();
                } catch (Exception ex) {
                    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }
    @Override
    protected void onPostExecute(String s) {
        TextView t = (TextView) getHelper().getInflater().inflate(R.layout.activity_main, null).findViewById(R.id.textView);
        t.setText("" + s); //has no effect on the UI but the text was set????
        Toast.makeText(getHelper().getContext(), t.getText(), Toast.LENGTH_LONG).show();
        super.onPostExecute(s);
    }
    @Override
    protected String doInBackground(String... params) {
        return getJSON("testside.com", 10000);
    }
    public Helper getHelper() {
        return helper;
    }
    public void setHelper(Helper helper) {
        this.helper = helper;
    }
}

谢谢:)

使用单独的文件

,在主类外部利用您的异步
class MyActivity{
    new MyAsyncTask().execute();
}

您的异位施加作为另一个班级延伸异步

的生活
class MyAsyncTask extends AsyncTask{
    public MyAsyncTask(Context appContext){
    }
}

一定要通过应用程序的上下文。您只能执行任务的每个实例。...但是,您可以在需要时创建并运行新实例...

不会飞:

    class MyActivity{
        MyAsyncTask myTask = new MyAsyncTask();
        myTask.execute();
        //DO OTHER STUFF
        myTask.execute();
    }

您将每次需要:

new MyAsyncTask().execute();

您的代码看起来不错,但它不起作用,因为它会引用您充气的new Layou的文本视图。

您有两个选择:

  1. 您想更改的辅助商店文本视图中,如果您的助手看起来像这样,则可以使其可选:

    public class Helper {
        private Context context;
        private LayoutInflater inflater;
        private TextView textView;
        ...       
        public void addTextView(TextView textView){
            this.texView = textView;
        }
        public TextView getTextView(){
            return textView;
        }
    }
    

    ,然后在您的postexecute()中调用 TextView t = helper.getTextview()

  2. 直接将文本视图传递到您的异步箱,所以看起来像

    public MyAsyncTask(Helper helper, TextView t) {
        setHelper(helper);
        this.textView = t;
    }
    

在背景线程上执行您的异步。要更新您的UI电话,

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        textView.setText("Text");
    }
});

在活动上。

最新更新