使用Toast显示casted int时,应用程序崩溃

时间:2013-05-13 11:35:54

标签: java android casting toast

我有一个Android应用程序调用PHP脚本,它返回0(FALSE)或1(TRUE) - 不幸的是作为字符串。所以在我的Java代码中,我有变量String result,它是“0”或“1”。我知道(感谢你们这里的人),这个字符串可以从BOM开始,所以我删除它,如果它。

这不是必要的,但是如果我将结果作为整数而不是字符串,我会感觉更好。从字符串到名为code的int的转换似乎有效。至少我没有看到任何事情发生。

但是当我想使用像if (code == 1)这样的casted int或通过Toast显示它时,我的应用程序崩溃了。 我可以使用Toast显示result == "1"result.length() == 1所以我看不出如何将此字符串转换为int:

String result = postData("some stuff I send to PHP");

if (result.codePointAt(0) == 65279) // which is the BOM
   {result = result.substring(1, result.length());}

int code = Integer.parseInt(result); // <- does not crash here...

// but here...
Toast.makeText(ListView_Confirmation.this, code, Toast.LENGTH_LONG).show();

我还尝试使用valueOf()并添加.toString(),但它只是一直崩溃。我在这里缺少什么?

5 个答案:

答案 0 :(得分:4)

  Use the following way to show toast 
    Toast.makeText(ListView_Confirmation.this, ""+code, Toast.LENGTH_LONG).show();

答案 1 :(得分:2)

Toast.makeText需要String(CharSequence)int,但此int表示要使用的字符串资源的资源ID(例如:R.string.app_name

尝试改为:

Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();

答案 2 :(得分:1)

使用以下

Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#valueOf(int)

public static Toast makeText(Context context,CharSequence text,int duration)

制作一个只包含文字视图的标准吐司。

参数

context      The context to use. Usually your Application or Activity object.
text         The text to show. Can be formatted text.
duration     How long to display the message. Either LENGTH_SHORT or LENGTH_LONG

http://developer.android.com/reference/android/widget/Toast.html

因此使用String valueOf(code)作为makeText(params)的第二个参数

返回整数(代码)参数的字符串表示形式。

答案 3 :(得分:0)

根据 Toast Toast.makeText(Context, int, int)使用该整数作为资源ID来查找资源中的字符串。 现在,由于您没有具有相同整数的资源,该函数将抛出Resources.NotFoundException

因此,要显示 int 值,您必须将其更改回文本。

Toast.makeText(ListView_Confirmation.this, String.valueOf(code), Toast.LENGTH_LONG).show();

答案 4 :(得分:0)

在android Api中,toast的构造函数是: Toast.makeText(Context context,int resId,int duration)

“resId”是String的引用,但不是String对象的引用:

示例:resId = R.string.helloworld