ArrayIndexOutOfBoundsException异常

时间:2014-07-24 09:40:44

标签: android

我在代码中获得ArrayIndexOutOfBoundsException,请问哪里有问题。 以及如何解决这个问题 以下是我的活动代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.textview = (TextView) findViewById(R.id.textView1);

    // HTTPConnector http = new HTTPConnector();
    GetAllDataTask get = new GetAllDataTask();
    get.execute();
}

public void setTextToTextView(JSONArray jsonArray) {

    String s = "";
    for (int i = 0; i < jsonArray.length(); i++) {

        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(i);

            s = s + "\n" + "Name =" + json.getString("name") + "\n"
                    + "Contact number = " + json.getInt("contact") + "\n"
                    + "Categroy = " + json.getString("Category");
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(),
                    "there is some problem", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    this.textview.setText(s);
}

private class GetAllDataTask extends
        AsyncTask<HTTPConnector, Long, JSONArray> {

    @Override
    protected JSONArray doInBackground(HTTPConnector... arg0) {
        // TODO Auto-generated method stub
        return arg0[0].GetAllData();
    }

    @Override
    protected void onPostExecute(JSONArray jsonArray) {
        // TODO Auto-generated method stub
        setTextToTextView(jsonArray);
    }

}

以下是我从这个问题得到的堆栈跟踪的一部分:

07-24 14:27:36.059: E/AndroidRuntime_2_crash(27865): crash in the same process: 
07-24 14:27:36.059: E/AndroidRuntime_2_crash(27865): java.lang.RuntimeException: An error occured while executing doInBackground()
07-24 14:27:36.059: E/AndroidRuntime_2_crash(27865):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-24 14:27:36.059: E/AndroidRuntime_2_crash(27865): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

2 个答案:

答案 0 :(得分:1)

问题在于:

@Override
protected JSONArray doInBackground(HTTPConnector... arg0) {
    // TODO Auto-generated method stub
    return arg0[0].GetAllData();
}

您正在获取HTTPConnector数组的第一个索引,但您从未将任何HTTPConnector传递给AsyncTask

GetAllDataTask get = new GetAllDataTask();

// Here you need to pass a HTTPConnector to the AsyncTask
get.execute();

所以你需要做这样的事情:

GetAllDataTask get = new GetAllDataTask();
get.execute(httpConnector);

答案 1 :(得分:0)

例如,当您的数组大小小于迭代时,会出现ArrayIndexOutOfBounds异常 如果你的数组的大小是5并且你试图访问不可行的数组的第6个元素那么这样的异常会出现

在你的情况下

我认为JSONArray.length的长度是问题,请通过调试器检查 这就是为什么你的代码会出现这种异常的原因