[안드로이드] android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

프로그래밍/Android 관련2017. 12. 26. 21:24
안녕하세요. 개발자 드리머즈입니다.

AlertDialog 테스트 중에 아래와 같은 에러가 발생했습니다.

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 


문제가 되었던 코드는 아래의 코드입니다.(LoginActivity.java)

AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
alert.setTitle("타이틀");
alert.setMessage("메세지");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Todo
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Todo
}
});
alert.show();


스택오버플로우를 찾아보니.. 구글의 버그 같습니다.

Android documents suggests to use getApplicationContext();

but it will not work instead of that use your current activity while instantiating AlertDialog.Builder or AlertDialog or Dialog...

Ex:

AlertDialog.Builder builder = new  AlertDialog.Builder(this);

or

AlertDialog.Builder builder = new  AlertDialog.Builder((Your Activity).this); 


그래서 위의 답변대로 AlertDialog.Builder()의 인자에
getApplicationContext()가 아닌
LoginActivity.this를 넣어주니 정상적으로 동작합니다.
AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
alert.setTitle("타이틀");
alert.setMessage("메세지");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Todo
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Todo
}
});
alert.show();



*참고

stackoverflow 질문글 : https://stackoverflow.com/questions/2634991/android-1-6-android-view-windowmanagerbadtokenexception-unable-to-add-window

작성자

Posted by 드리머즈

관련 글

댓글 영역