将上下文传递给Async类

时间:2015-07-20 08:11:56

标签: java android

我正在从我的主要活动课程中调用Async课程。执行POST后,我想将结果返回给主活动。

public class MainActivity extends Activity implements OnClickListener, AsyncResponse{
    public Context context;
    PostKey asyncTask = new PostKey(context);

    public void onCreate(Bundle savedInstanceState) {
        asyncTask.delegate = this;
    }

    public void onClick(View v) {
        asyncTask.delegate = this;
        new PostKey(context).execute(keyValue);
    }

    public void processFinish(String output){
        //this you will received result fired from async class of    onPostExecute(result) method.
        Log.d("Result", output);
    }
}


public class PostKey extends AsyncTask<String, String, String> {
    public AsyncResponse delegate = null;
    public Context context;

    public PostKey(Context context){
        this.context = context.getApplicationContext();
    }

    @Override
    protected String doInBackground(String... params) {
        return postData(params[0]);
    }

    @Override
    protected void onPostExecute(String result){
        this.context = context.getApplicationContext();
        delegate = (AsyncResponse) context;
    }

    delegate.processFinish(result);
}

public interface AsyncResponse {
    void processFinish(String output);
}

每当我尝试运行应用程序时,我立即得到由nullpointer异常引起的致命错误。 nullpointer指的是:

public PostKey(Context context){
    this.context = context.getApplicationContext();
}

&安培; PostKey asyncTask = new PostKey(context);

在第二种情况下,我可以得到context为空,但我必须在这里传递变量。

3 个答案:

答案 0 :(得分:2)

Activity已经是Context,因此您不要保留对它的引用。只需使用this即可。另一方面,Activity必须经过其生命周期才能使用上下文。删除

public Context context;
PostKey asyncTask = new PostKey(context);

并添加

PostKey asyncTask = new PostKey(this);

onCreate中。请在super.onCreate(savedInstanceState);

中添加onCreate作为第一件事

答案 1 :(得分:0)

你好Oryna你在参数中传递空上下文值只是用这个

替换这些行
 new PostKey(context).execute(keyValue);

 new PostKey(MainActivity.this).execute(keyValue);

并且异步任务的构造函数替换代码

    public PostKey(Context context){
    this.context = context.getApplicationContext();
}

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

答案 2 :(得分:0)

尝试使用this.context = getApplicationContext();代替