开发者

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.sendMessag开发者_开发技巧e(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.


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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜