String数组抛出索引越界异常

时间:2014-11-12 11:51:33

标签: java android arrays indexoutofboundsexception

我正在创建一个Android应用程序,这部分是光标将通过数据库并存储'标题'表的一部分变成了一个字符串数组。然后在另一个类中调用它,用于根据条目动态显示按钮。将标题放入数组的代码如下:

public String[] getTitles()
{
    SQLiteDatabase db =getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, SPORTS_TABLE_NAME);
    String title;
    String[] titleArray = new String[100];
    String sql = "SELECT Title FROM Sports;";
    Cursor cursor = db.rawQuery(sql, null);
    int i = 1;

    while (cursor.moveToNext()) {

        if(cursor != null && cursor.moveToFirst()) {
            title = cursor.getString(0);
            titleArray[i] = title;
            i++;
        }
        if(cursor != null)
            db.close();

    }
    cursor.close();
    return titleArray;
}

然后使用以下代码调用它:

int i = 1;

    String[] titlesArray = db.getTitles();
    for(String titles: titlesArray){
        Button btn = new Button(this);
        btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btn.setId(i);
        btn.setText(titlesArray[i]);
        ll.addView(btn);
        i++;
    }

一直在寻找并认为它需要一双新鲜的眼睛..任何想法?

1 个答案:

答案 0 :(得分:4)

如果您的查询返回超过100行怎么办?如果认为使用像

这样的东西会更安全
String sql = "SELECT Title FROM Sports;";
Cursor cursor = db.rawQuery(sql, null);
if (cursor == null)
   return;
String[] titleArray = new String[cursor.getCount()];
 while (cursor.moveToNext()) {
     title = cursor.getString(0);
     titleArray[i] = title;
     i++;  
}

,更好,一个集合。

String sql = "SELECT Title FROM Sports;";
Cursor cursor = db.rawQuery(sql, null);
if (cursor == null)
      return;
ArrayList<String> titleArrayList = new ArrayList<String>();
while (cursor.moveToNext()) {
     title = cursor.getString(0);
     titleArrayList.add(title);       
}