Handler HandleMessage not fired from AsyncTask

  • Replies:3
Simon Williams
  • Forum posts: 5

Aug 3, 2011, 4:29:25 PM via Website

Hi,

I have an AsyncTask that is doing some processing but when it is finished I cannot get it to fire the HandleEvent method af a Handler object (I hope that terminology is correct).

Here is my code:

public class main extends Activity {
/** Called when the activity is first created. */
public Handler mHandler;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// code here to start the background task - all working fine

mHandler = new Handler() {
public void HandleMessage(Message msg) {
Log.v("Handler", "in HandleMessage");
}
};
}
}

final class SendItemToServer extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground (Void ... arg0) {
// some code here to connect to my server - all this is working, data is saved on the server
mHandler.sendEmptyMessage(0);
return 0;
}

@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
}

The error is on the line mHandler.sendEmptyMessage(0); in the AsyncTask - the error is "mHandler cannot be resolved".

Thanks for any help.

Simon

Reply
Jeremiah
  • Forum posts: 775

Aug 4, 2011, 2:00:36 AM via Website

I think you have a scope problem here. When a variable cannot be resolved, its saying that it was never declared or is not in the scope it's used in. mHandler is public in your "main" class, but is out of scope in your "SendItemToSever" class. Try passing mHandler to your "SendItemToServer" class before using it.

Reply
Simon Williams
  • Forum posts: 5

Aug 4, 2011, 10:34:53 AM via Website

Hi Jeremiah,

This was indeed the cause of the problem.

Being new to Java (as well as Android) I was not aware that you could define a class within another class.

To resolve the problem I moved the class SendItemToServer to be inside the class main (and changed it to public class instead of final class).

Now on to the next problem.......

Thanks for your help.

Simon

— modified on Aug 4, 2011, 10:35:10 AM

Reply