showDialog() is accessing old View => Error: Activity has leaked window [...]
I am writing the app and I have the following scenario: First i show an Acitivty and I show a ProgressDialog while loading data from a Server. I do the loading task in a Thread because I found this to be a solution so that the Dialog is shown correctly
showDialog(DIALOG_LOAD);
loadListThread = new Thread(new Runnable(){
@Override
public void run(){
service.execRequest();
loadingFinishedHandler.sendEmptyMessage(0);
MyActivity.this.dismissDialog(MyActivity.DIALOG_LOAD);
}
});
loadListThread.start();
After the Thread is finished I notify a Handler. Again this is a solution I found for the problem to access Views in the activity without being in the Thread anymore
loadingFinishedHandler = new Handler(){
@Override
public void handleMessage(Message msg){
showList();
}
};
After loading is finished, I check whether I received data correctly. If not, i want to show an error dialog:
showDialog(DIALOG_ERROR);
I call the dialogs with the onCreateDialog method
public Dialog onCreateDialog(int dialogId){
switch(dialogId){
case DIALOG_LOAD:
String message = getString(R.string.load);
ProgressDialog loadDialog = new ProgressDialog(this);
loadDialog.setMessage(messa开发者_JS百科ge);
loadDialog.setCancelable(false);
return loadDialog;
case DIALOG_ERROR:
String message = getString(R.string.error);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(errorMessage);
builder.setNeutralButton(getString(R.string.ok), null);
return builder.create();
}
return null;
}
And here is the problem: If I change the Orientation of my phone while data is loading and an error dialog shall be created afterwards, I get this message
Activity [...] has leaked window [...] that was originally added here
I understand why this is happening. The View has been re-created, when i rotated my phone and showDialog() is obviously trying to access the old one. But I do not know how to fix it.
Does anyone has an idea?
Edit: solved it :-) I found out that I can prevent my Activity from restarting on orientation change. I read about it in this article Handling Runtime Changes
I declared in the AndroidManifest by adding
android:configChanges="orientation"
that i handle orientation changes by myself. These changes can now be handled with this method
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
But for my case it was not necessary to add any code!
public Dialog onCreateDialog(int dialogId){
if(isFinishing()){
return null;)}...
精彩评论