Java不会Integer.parseInt(字符串)

时间:2015-08-20 20:08:59

标签: android string-parsing

这是我的网站:http://daniandroid.honor.es/getAllCustomers.php 当您访问该网站时,您会得到一个简单的文字“500”。

行。

 final ourHTTP hi = new ourHTTP();

        out_string = hi.getWebPage("http://daniandroid.honor.es/getAllCustomers.php");

getWebPage返回字符串(内容)。

 int veriff = Integer.parseInt(out_string);

         if(veriff>1)
         {
             final_form.setText("ya");
         }

final_form 是我的xml文件中的 TextView activity_second.xml

应用程序将崩溃。 ERROR:

at com.android.interval.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)

Caused by: java.lang.NumberFormatException: Invalid int: "500"
at java.lang.Integer.parse(Integer.java:375)

如果我用这个

替换out_string
out_string= "500";
一切都很好。

我的 getAllCustomers.php 文件包含(来源):

<?php
echo"500";
?>

以下是获取内容的方法。

public String getWebPage(String adress)
{
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet();

    InputStream inputStream = null;
    String response = null;


    try{
        URI uri = new URI(adress);
        httpGet.setURI(uri);

        HttpResponse httpResponse = httpClient.execute(httpGet);


        inputStream = httpResponse.getEntity().getContent();
        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        int inChar;
        StringBuffer stringBuffer = new StringBuffer();

        while((inChar = reader.read()) != -1){

            stringBuffer.append((char)inChar);
        }

        response = stringBuffer.toString();

    }catch(ClientProtocolException e)
    {
        Log.e(adress, "error");
    }catch(IOException e)
    {
        Log.e(response, "error");
        //
    }catch(URISyntaxException e)
    {
        Log.e(response, "error"); 
    }

    return response;
    }

3 个答案:

答案 0 :(得分:1)

您的回复可能在内部包含""字符串,只需替换""

就这样,

out_string = hi.getWebPage("http://daniandroid.honor.es/getAllCustomers.php");

if(out_string.contains("\"")) // change according to your response, if it contains other charcter
{
 out_string = out_string.replace("\"", "")
}

try
{
 int veriff = Integer.parseInt(out_string);

 if(veriff>1)
 {
  final_form.setText("ya");
 } 
}catch(NumberFormatException ex)
{
   // Handle exception
}

我建议你也要处理Exception,如果你的resposnse中有其他无效字符,可能就是这样。

答案 1 :(得分:1)

如评论中所述:

我认为你的HTTP lib会传递一些非十进制字符和输出。试试这个:

int veriff = Integer.parseInt(out_string.replaceAll("[\\D]",""));

[\\D]是正则表达式,表示任何非小数字符。

答案 2 :(得分:0)

对于您正在运行的Java版本,请检查代码。 java.lang.Integer.parse(Integer.java:375)

粗暴地使用Firebug并检查响应
我看到“500”,这肯定超过了我预期的“500”。