我正在調用我主要活動類中的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);
}
每當我嘗試運行應用程序,我立刻得到所引起的空指針異常的致命錯誤。該空指針指的是以下幾點:
public PostKey(Context context){
this.context = context.getApplicationContext();
}
& PostKey asyncTask = new PostKey(context);
在第二種情況下,我可以得到context
是空的,但我要在這裏傳遞變量。
在您的主要活動,'公共上下文的背景下;'聲明,但從未給予價值?它是空的..所以試圖調用PostKey構造函數,試圖調用null對象上的'getApplicationContext()'函數肯定會給你一個NullPointerException。 – Gosu
可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) – Gosu
@Gosu在每個代碼片段中,我發現'context'變量是在async類中設置的。由於'私人PostKey(上下文上下文){}'我必須在主要活動中傳遞變量 – Orynuh