Я вызываю класс Async
из своего основного класса активности. Когда был выполнен POST
, я хочу вернуть результат к основному действию.Передать контекст классу Async
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
пуст, но я должен передать переменную здесь.
В вашей основной деятельности, 'контексте общественного контекста,' объявлен, но никогда не присваивается значение? Это значение null .. поэтому попытка вызвать конструктор PostKey, который пытается вызвать функцию getApplicationContext() на нулевом объекте, определенно даст вам исключение NullPointerException. – Gosu
Возможный дубликат [Что такое исключение Null Pointer Exception и как его исправить?] (Http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) – Gosu
@Gosu В каждом фрагменте кода я обнаружил, что переменная 'context' была установлена в классе async. Из-за 'private PostKey (контекст контекста) {}' Мне нужно передать переменные в основной активности – Orynuh