获得异常StringIndexOutOfBoundsException

时间:2013-05-24 12:58:55

标签: android

我在使Java方法正常工作方面遇到了一些问题。在程序中,我创建了一个由不同长度的许多不同单词组成的数组。我正在处理的方法应该取一个字符串的前3个字母。我正在使用obj.substring(0,3)。但我得到StringIndexOutOfBoundException。有谁可以帮我解决这个问题。 这是我的代码:

            private void singleCurrencyAsynctaskCaller() {
    isSingleCurrencyResultOk = false;
    String from = subSpinner1.getSelectedItem().toString().trim();
    String to = subSpinner2.getSelectedItem().toString().trim();
    String from1 = from.substring(0, 3);
    String to1 = to.substring(0, 3);

    if (!from1.equals(to1)) {
        String RESTURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"
                + from1
                + to1
                + "%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

        AsyncTaskSingleCurrency singleCurrencyAsyncTask = new AsyncTaskSingleCurrency(
                ConverterActivity.this,
                new FetchSingleCurrencyTaskCompletedListner());
        singleCurrencyAsyncTask.execute(RESTURL);

    } else {

        currencySingleRate = 1.0;
        isSingleCurrencyResultOk = true;
        callCurrencyLogic(true);
    }
}

我遇到了这个例外:

            java.lang.StringIndexOutOfBoundsException in java.lang.String.substring

            java.lang.StringIndexOutOfBoundsException
           at java.lang.String.substring(String.java:1579)
            at   com.zyksa.converter.
        ConverterActivity.singleCurrencyAsynctaskCaller(ConverterActivity.java:402)
         at com.zyksa.converter.ConverterActivity.onClick(ConverterActivity.java:580)
         at android.view.View.performClick(View.java:2408)
       at android.view.View$PerformClick.run(View.java:8816)
       at android.os.Handler.handleCallback(Handler.java:587)
        at android.os.Handler.dispatchMessage(Handler.java:92)
       at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:4627)
       at java.lang.reflect.Method.invokeNative(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:521)

2 个答案:

答案 0 :(得分:0)

试试这个:

String from1 = from.substring(0, 2);
String to1 = to.substring(0, 2);

答案 1 :(得分:0)

可能是你的String长度还不够。试试这个:

String yourString;
.
.
String subString;
if (yourString.length() > 3)
    subString = yourString.substring(0, 3);
else
     // Do something else

在你的情况下

String from1, to1;
if(form.length() > 3)
     from1 = from.substring(0, 3);
else
     // Do somthing else

if(to.length() > 3)
     to1 = to.substring(0, 3);
else
     // Do somthing else