Toast is crashing Application, even inside thread

只愿长相守 提交于 2019-11-28 12:44:07

You need to use runOnUiThread

Something like

 runOnUiThread(new Runnable() {
            public void run()
            {
                Toast.makeText(ctx, toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

Toast is a UI element so it needs to run on the UI Thread, not a background Thread.

However, if this is all you are using it for then you don't need a separate Thread just to show a Toast. If you can explain the context of how you are using it then maybe we can help with a better way. Also, if you are inside of your Activity then you don't need a variable for Context. You can use ActivityName.this instead to access the Activity Context

You likely don't have your ctx variable instantiated, so you are getting NULL Pointer.

You should not put this in a Thread, and is actually a pretty bad idea (knowing you are just getting started).

execute: adb logcat to see your log output.

You don't need a different thread, your ctx variable is probably the one causing it, try using getApplicationContext(), this should work:

import android.widget.Toast;

Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_LONG).show();
kamran hatami

Only the mainthread can change the UI. That's why your application crashes. Do your work on the mainthread, and if you are doing something heavy like network or IO, you should use AsyncTask because each thread has 5 seconds to respond.

You can do this like this.

((Button)findViewById(R.id.myButton)).setOnClickListener(new OnClickListener(){
    public void onClick(View v) {
        Toast.makeText(MyActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
    }
});

Where:

  • myButton is the id of your view
  • myActivity is your activity

I hope this will help you.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!