AsyncTask中的Android setText对UI

时间:2016-12-03 17:00:46

标签: android android-asynctask

我遇到与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;
    }
}

谢谢:)

3 个答案:

答案 0 :(得分:0)

使用单独的文件

在主类之外使用AsyncTask
class MyActivity{
    new MyAsyncTask().execute();
}

你的AsyncTask是另一个类Extending AsyncTask

class MyAsyncTask extends AsyncTask{
    public MyAsyncTask(Context appContext){

    }
}

请务必传入App的上下文。您只能执行一次任务的每个实例....但您可以在需要时创建并运行新实例...

不会飞:

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

您可以在每次需要时执行此操作:

new MyAsyncTask().execute();

答案 1 :(得分:-1)

您的AsyncTask在后台线程上执行。要更新您的UI调用,

runOnUiThread(new Runnable() {

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

});

活动。

答案 2 :(得分:-1)

您的代码看起来很好,但它不起作用,因为它引用了您膨胀的新布局中的TextView。

您有两种选择:

  1. 在您要更改的帮助商店TextView中,如果您的助手看起来像这样,您可以选择它:

    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. 将textView直接传递给AsyncTask,使其看起来像

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