備忘録 〜プログラミング〜

プログラミングに関する事をつらつらと、、

AlertDialog.BuilderでBadTokenException

DialogFragmentをカスタマイズするときに、BadTokenExceptionが出たのでメモ。
まず、AlertDialogを出すために、こんな感じでAlertDialigを生成しました

private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState)
  mContext = getApplicationContext();
  AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTItle("sample").setMessage("sample");
  AlertDialog dialog = builder.create();
  dialog.show();
}

はい。

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

出ました。
どうやら、AlertDialog.Builderの引数で渡したコンテキストが問題だったようです。

AlertDialog.Builder(mContext)

これを、こう

AlertDialog.Builder(MyActivity.this);

無事、ダイアログを呼び出す事が出来ましたー

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