티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

getApplication()을 context로 사용하면 "Unable to add window — token null is not for an application” 오류가 발생합니다.

 문제 내용 

My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:

제 Activity에서는 Context 매개 변수가 필요한 AlertDialog를 만들려고 합니다. 다음과 같이 사용하면 예상대로 작동합니다:
AlertDialog.Builder builder = new AlertDialog.Builder(this);

 

However, I am leery of using "this" as a context due to the potential for memory leaks when Activity is destroyed and recreated even during something simple like a screen rotation. From a related post on the Android developer's blog:

하지만, 화면 회전과 같은 간단한 작업 중에도 Activity가 파괴되고 다시 만들어지는 경우에도 메모리 누수의 가능성 때문에 "this"를 Context로 사용하는 것에 대해 신중해야합니다. Android 개발자 블로그의 관련 게시물에 따르면:

 

There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().

컨텍스트 관련 메모리 누수를 피하는 두 가지 쉬운 방법이 있습니다. 가장 명백한 방법은 해당 컨텍스트의 스코프를 벗어나지 않도록 하는 것입니다. 위의 예시는 정적 참조의 경우를 보여주었지만, 내부 클래스와 외부 클래스의 암묵적 참조 역시 위험할 수 있습니다. 두 번째 방법은 어플리케이션 컨텍스트를 사용하는 것입니다. 이 컨텍스트는 앱이 실행되는 동안 생명 주기를 유지하며 액티비티의 생명 주기에 의존하지 않습니다. 컨텍스트가 필요한 오래 지속되는 객체를 유지할 계획이라면, 어플리케이션 객체를 기억해두세요. Context.getApplicationContext() 또는 Activity.getApplication()을 호출하여 쉽게 가져올 수 있습니다.

 

But for the AlertDialog() neither getApplicationContext() or getApplication() is acceptable as a Context, as it throws the exception:

하지만 AlertDialog()에서는 getApplicationContext()나 getApplication()을 Context로 사용할 수 없으며 다음과 같은 예외가 발생합니다.

 

"Unable to add window — token null is not for an application”

 

per references: 1, 2, 3, etc.

참조: 1, 2, 3 등

 

So, should this really be considered a "bug", since we are officially advised to use Activity.getApplication() and yet it doesn't function as advertised?

그래서, Activity.getApplication()을 사용할 것을 공식적으로 권장하면서도 실제로 예상대로 작동하지 않기 때문에 이것이 실제로 "버그"로 간주되어야 할까요?

 

 

 

 

 높은 점수를 받은 Solution 

Instead of getApplicationContext(), just use ActivityName.this.

getApplicationContext() 대신에 ActivityName.this를 사용하세요.

 

 

 

 가장 최근 달린 Solution 

Just use following:

다음을 사용하세요:

 

FOR JAVA USERS

Java 사용자를 대상으로

 

In case you are using activity --> AlertDialog.Builder builder = new AlertDialog.Builder(this);

만약 액티비티를 사용하는 경우 --> AlertDialog.Builder builder = new AlertDialog.Builder(this);

 

OR

또는

 

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

In case you are using fragment --> AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

플래그먼트를 사용한다면 : AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

 

FOR KOTLIN USERS

예를 들어 액티비티를 사용하는 경우 -> AlertDialog.Builder(this)

 

In case you are using activity --> val builder = AlertDialog.Builder(this)

액티비티를 사용할 경우 --> val builder = AlertDialog.Builder(this)

 

OR

또는

 

val builder = AlertDialog.Builder(this@your_activity.this)

In case you are using fragment --> val builder = AlertDialog.Builder(activity!!)

fragment를 사용하는 경우 --> val builder = AlertDialog.Builder(activity!!)

 

 

 

출처 : https://stackoverflow.com/questions/5796611/dialog-throwing-unable-to-add-window-token-null-is-not-for-an-application-wi

반응형
댓글
공지사항
최근에 올라온 글