Search code examples
javaandroidtoast

Toast not working (Android)


When I run this method Toast.makeText(MainActivity.this, txt, Toast.LENGTH_LONG).show(); from another thread, the application falls to be working only from the onCreate, but DebugText.setText(txt);

works fine everywhere ... who else can help?

public void screenMessage(final String txt) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
               //DebugText.setText(txt);
                Toast.makeText(MainActivity.this, txt, Toast.LENGTH_LONG).show();
            }
        });
    }

Solution

  • my solution as below(it works everywhere for me):

    public static void showToast(final Context ctx, final String msg, int type) {
        if (ctx == null || TextUtils.isEmpty(msg))
            return;
        final int toastType = type == Toast.LENGTH_LONG ? Toast.LENGTH_LONG
                : Toast.LENGTH_SHORT;
        if (Looper.myLooper() == Looper.getMainLooper()) {
            Toast.makeText(ctx, msg, toastType).show();
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, toastType).show();
                }
            });
        }
    }