开发者

Android: Activity closing when in dialog

I have a strange situation I am seeing.

I am reading some info from a database , then bringing up a dialog : PSEUDO

 val = DBaseManager.readValue(i,POS_ONE);

 if(val == 1)
 {
   Dialog_Test myDialog = new 
   Dialog_Test (myContext,"",new addListener(),DBaseManager);
   myDialog.show();
 }

as you can see I pass into the Dialog the DBaseManager so it can use it also.

then in there I use it like this :

DBaseManager.readValue(k,POS_TWO);

etc.

Now this works 99% of the time, however I have had some crash logs pointing to these lines in the dialog with null pointer exceptions.

To me this is indicating that on some devices my onPause or OnDestory methods are being called in the main activity which closes and nulls DBaseManager. These are 1.6, 2.2 and 2.3 devices.

So the question 开发者_运维知识库is why , and how to prevent ? I have added some null pointer checks in to prevent the crashes but it still far from ideal.

UPDATE: On my devices at least when I do a screen rotate the activity is restarted and the dialog disappears - could it be on some the dialogs remains up???


This probably depends on the scope of your Dialog and where in the code you are opening it. The default behavior is for the Activity to go through its lifecycle when the orientation changes unless you explicitly handle orientation changes and override onOrientationChanged. You might want to do something like maintain the state of your dialog at the Activity level (such as adding a boolean isDialogDisplayed as a class variable) and then in onCreate or onResume check that and reopen the dialog.

As far as the DBaseManager object being cleaned up, I have experienced similar things. Large objects getting cleaned up when you don't expect them to (there are still pointers to these objects, but they've been nulled by the system somehow). I've identified these in my applications and just been more careful. Instead of null checking and reloading when null only when it's possible that your code could have nulled the variable (or using lazy loading), I'd always treat this object as if it were lazy loaded. Add a method that returns this object instead of accessing it directly, and always check for null and reload if it is.

For both of these two issues, you might want to override all the lifecycle methods of this Activity and log them. Don't forget to call the lifecycle methods on the base class within your overrides (ie. public void onPause() { super.onPause() ..., etc)!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜