我无法使用AsyncClass中的findViewById

时间:2014-02-10 19:26:16

标签: java android android-asynctask textview findviewbyid

我无法使用我的Kclass中的findViewById() =(我怎么能用它?`

private class BackGroundTask extends AsyncTask<Void, Void, Void>{



    @Override
    protected Void doInBackground(Void... params) {
        try {
            //execute - means sending
        response =httpClient.execute(request);
        HttpEntity entity=response.getEntity();
        String str=EntityUtils.toString(entity);
        Log.v("Json=", str);
        //adding new response to our Response Class
        resp.addNewResponse(str);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, "Exception caught: ", e);
        }
        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        httpClient.getConnectionManager().shutdown();
        TextView textView = (TextView) findViewById(R.id.textView1);

        textView.setText("Done");
    }


  }
}

请写一个确切的代码。该类位于另一个.java文件中。不在MainActivity.java

3 个答案:

答案 0 :(得分:4)

最简单的方法是根本不使用findViewById(),因为您在一个单独的文件中并且是Activity方法。

您只需使用interfacecallback中创建onPostExecute(),然后将String结果发回给Activity。然后在callback中,您只需根据需要设置文字即可。

This answer gives an example of using an interface with AsyncTask

答案 1 :(得分:0)

您可以将Activity上下文(YourActivity.this)传递给AsyncTask并使用activity.findViewById(...);

修改 一些代码:

添加到AsyncTask:

private Activity mActivity;

public YourAsyncTask(Activity activity){
this.mActivity = activity
}

... 
....

protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    httpClient.getConnectionManager().shutdown();
    if(mActivity!=null){
        TextView textView = (TextView) mActivity.findViewById(R.id.textView1);
    }
    textView.setText("Done");
}

答案 2 :(得分:0)

private Activity activity;

并在构造函数中:

public BackGroundTask(Activity activity){
    this.activity=activity;
}

并在后执行:

 protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    httpClient.getConnectionManager().shutdown();
    TextView textView = (TextView) activity.findViewById(R.id.textView1);

    textView.setText("Done");
}

如果从活动类调用创建新的背景类:

BackGroundTask doItInBackGround = new BackGroundTask(this);

如果在Click监听器或Activity内部的任何类中调用:

BackGroundTask doItInBackGround = new BackGroundTask(ActivityName.this);