I am using a subclass inside my main activity to do an asynctask. I plan to move it into a separate file afterwards I just prefer doing it this way to confirm it is working. I am trying to do a HTTPRequest with a progress dialog because of the potentially long waiting times. I am doing nothing in the doInBackground() because I’ve read you cannot access the UI layer from there. Ultimately what is happening is I show my progress dialog on onPreExecute() and dismiss it in onPostExecute(). I am calling each task separately above which could be 99% of my problem but I need to be able to pass my activity to the tasks for them to function properly.
I’ve broken a lot of the steps down into little pieces. I am getting a null pointer exception which leads me to believe my problem comes from not using execute() but I just can’t seem to figure out how that works.
new CodeRetrievalItem().onPreExecute(MyActivity.this);
new CodeRetrievalItem().onPostExecute(MyActivity.this);
class CodeRetrievalItem extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
protected void onPreExecute(Activity actpass){
dialog = new ProgressDialog(actpass);
dialog.setMessage("Loading");
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(Activity actpass){
// Execute HTTP Request
try{
dialog.dismiss();
}
catch(Exception e){
Toast.makeText(actpass, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
}
}
}
You are using
AsyncTaskcompletely wrong. There are several major mistakes in your code.AsyncTask protected methods
Do not call them yourself. In the documentation for AsyncTask, you can find:
You have to start your
AsyncTaskby callingexecute(Params...)method. This will cause that:onPreExecute()is called prior to the start of background execution and is called on the main threaddoInBackground(Params...)is called in backgroundonPostExecute(Result)is called on the main thread.Unless you call
execute(Params...)nothing of this will happen.Generic parameters
Moreover there is a problem with your generic parameters.
AsyncTaskhas three generic paramtersAsyncTask<Params, Progress, Result>(in your caseAsyncTask<Void, Void, Void>, you have to match these parameters in the methods’ parameters.Therefore create:
onPreExecute()instead ofonPreExecute(Activity actpass)onPostExecute(Void)instead ofonPostExecute(Activity actpass)Those methods you defined aren’t bound to the async execution in any way, they are just some extra methods in the class.
If you need to access the activity inside the
AsyncTaskpass it in different way (e.g. in a constructor). Beware that passing anActivityto anAsyncTaskmight lead to possible memory leaks (it’s good to utilizeWeakReference<T>here) and accessing dialogs inonPostExecute(Result)might cause crash if not properly handled.