吐司崩溃应用程序,甚至是内螺纹 [英] Toast is crashing Application, even inside thread

查看:180
本文介绍了吐司崩溃应用程序,甚至是内螺纹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个onClick事件在我的Andr​​oid应用程序触发以下code,但它让我崩溃的应用程序。我把它放在一个线程不仅是因为我读的是应该以prevent崩溃。此外CTX指活动的情况下(这是我在活动设置等于此创建一个变量。我已阅读并尝试了几件事情。任何帮助将是真棒,谢谢!

 发toastThread =新的Thread(){
  公共无效的run(){
    吐司alertFailure = Toast.makeText(CTX,登录失败,Toast.LENGTH_LONG);
    alertFailure.show();
  }
};
toastThread.start();
 

解决方案

您需要使用<一个href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread%28java.lang.Runnable%29">runOnUiThread

类似于

  runOnUiThread(新的Runnable(){
            公共无效的run()
            {
                Toast.makeText(CTX,烤面包,Toast.LENGTH_SHORT).show();
            }
        });
    }
 

吐司 UI 元素,所以它需要在 UI线程中运行,而不是一个背景

但是,如果这是你正在使用它,那么你并不需要一个单独的只显示一个吐司。如果你能解释一下你是如何使用它,然后背景下,也许我们可以帮助您更好的办法。另外,如果你是你的活动的内部那么你就需要为上下文的变量。您可以使用 ActivityName.this 而不是访问活动上下文

I have an onClick event in my android app that triggers the following code but it keeps crashing my app. I put it in a thread only because i read that that's supposed to prevent crashing. Also ctx refers to the Activity's context (it's a variable I created in the activity set equal to this. I've read and tried several things. Any help would be awesome. Thanks!

Thread toastThread = new Thread() {
  public void run() {
    Toast alertFailure = Toast.makeText(ctx, "Login Failed", Toast.LENGTH_LONG);
    alertFailure.show();
  }
};
toastThread.start();

解决方案

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

这篇关于吐司崩溃应用程序,甚至是内螺纹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆