我正在从我的主要活动课程中调用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
为空,但我必须在这里传递变量。
答案 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();
代替