1

I have got a Fragment Activity that contains a textview and another class that extends AsyncTask. Now I would like to use the onPostExecute(String result) method to set the result text in my textview that is in my fragment activity.

How can I do that? I already created a custom constructor for the AsyncTask class that takes in a context object. How can I use that??

This is how I create a task object in my Fragment activity:

String query = "someText";
Task task = new Task(this.getActivity());
task.execute(query);

This is a snippet from my task class:

public class Task extends AsyncTask<String, Void, String> {

    private Context context;

    public Task (Context context) {
        this.context = context;
    }

    protected void onPostExecute(String result) {
    super.onPostExecute(result);
    // ??? What comes here ???
    }
}
4

4 回答 4

5
TextView txt = (TextView)((Activity)context).findViewById(R.id.watheveryouwant);
txt.setText("blabla");

但是你应该传递一个活动而不是一个上下文,会更容易;-)

或者

    public Task (Context context, TextView t) {
        this.context = context;
        this.t = t;
    }
   super.onPostExecute(result);
        t.setText("BlahBlah")
    }

应该做的伎俩

于 2013-08-14T14:48:35.993 回答
0

我从中选择了解决方案

如何从 AsyncTask 返回布尔值?

new Task(getActivity()).execute(query);

在构造函数中AsyncTask

TheInterface listener;
public Task(Context context)
{
  listener = (TheInterface) context; 
}

界面

public interface TheInterface {

public void theMethod(String result); // your result type

 }

然后

在您的 doInbackground 中返回结果。

在你的 onPostExecute

if (listener != null) 
{
  listener.theMethod(result); // result is the String
  // result returned in doInbackground 
  // result of doInbackground computation is a parameter to onPostExecute 
}

在您的活动类或片段中实现接口

public class ActivityName implements Task.TheInterface

然后

@Override
 public void theMethodString result) { 
    tv.setText(result); 
    // set the text to textview here with the result of background computation
    // remember to declare textview as a class member.
 }

编辑:

您还缺少 @Override 注释onPostExecute

于 2013-08-14T14:53:20.290 回答
0

您可以将 TextView 的实例作为参数传递给 AsynkTast,并在 onPostExecute 中调用 setText。

于 2013-08-14T14:53:33.020 回答
0

在您的情况下,只需执行以下操作:

((TextView)findViewById(R.id.xyz)).setText("abc");
于 2013-08-14T15:04:32.073 回答