티스토리 뷰

반응형

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

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

 

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

Can't create handler inside thread that has not called Looper.prepare()

"Looper.prepare()를 호출하지 않은 스레드 내에서 핸들러를 생성할 수 없습니다."오류 수정하기

 문제 내용 

What does the following exception mean; how can I fix it?

다음 예외는 무엇을 의미하며 어떻게 해결할 수 있는지 알려주세요.

 

This is the code:

이것이 코드입니다.
Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);

 

This is the exception:

이것은 발생하는 예외입니다
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
     at android.os.Handler.<init>(Handler.java:121)
     at android.widget.Toast.<init>(Toast.java:68)
     at android.widget.Toast.makeText(Toast.java:231)

 

 

 높은 점수를 받은 Solution 

You need to call Toast.makeText(...) from the UI thread:

UI 스레드에서 Toast.makeText(...)를 호출해야 합니다.
activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
  }
});

 

This is copy-pasted from another (duplicate) SO answer.

이것은 다른 (중복) SO 답변에서 복사 및 붙여넣기한 것입니다.

 

 

 

 가장 최근 달린 Solution 

Coroutine will do it perfectly

코루틴이 완벽하게 처리할 수 있습니다.
CoroutineScope(Job() + Dispatchers.Main).launch {
                        Toast.makeText(context, "yourmessage",Toast.LENGTH_LONG).show()}

 

 

출처 : https://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare

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