Realn0whereman
Realn0whereman

Reputation: 1226

Android thread handler NullPointerException

So this null pointer is confusing me. I believe it is a scope issue.

My main activity looks like this:

public class App extends Activity {  
  ProgressDialog progressDialog;  
  ProgressThread progressThread;

Then inside of the oncreate I do this:

  ProgressDialog progressDialog = new ProgressDialog(this);  
  progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  
  progressDialog.setMessage("Fetching Images...");  
  ProgressThread progressThread = new ProgressThread(handler,mImageIds,mImages);  
  progressThread.start();    
  progressDialog.show();

THEN inside progressThread which is a separate class I do

mHandler.sendMessage(mHandler.obtainMessage());

Now up until this point i believe it behaves as it should. I have my handler hanging out in class scope right underneath my oncreate

final Handler handler = new Handler() {  
  public void handleMessage(Message msg){  
    progressDialog.hide();  
    progressThread.interrupt();  
  }  
 };

The program thinks that progressDialog and progressThread are declared, but are null. Why would they be null if I instantiate in my oncreate.

Upvotes: 1

Views: 1479

Answers (3)

Realn0whereman
Realn0whereman

Reputation: 1226

Thanks Ian! I actually went ahead and reimplemented with AsyncTask. It is much cleaner and actually works better than it used to. Now I just need to implement a progressdialog with it.

Upvotes: 0

Ian G. Clifton
Ian G. Clifton

Reputation: 9439

ProgressDialog progressDialog = new ProgressDialog(this);

and

ProgressThread progressThread = new ProgressThread(handler,mImageIds,mImages);

are both declaring local variables. Change them to this:

progressDialog = new ProgressDialog(this);
progressThread = new ProgressThread(handler,mImageIds,mImages);

Upvotes: 1

mxk
mxk

Reputation: 43524

Before even starting to debug that, I would suggest using AsyncTask instead. It was created for worker threads that need to report progress on the UI thread.

Upvotes: 0

Related Questions