【问题标题】:String array throws index out of bounds exception字符串数组抛出索引超出范围异常
【发布时间】:2014-11-12 11:51:33
【问题描述】:

我正在制作一个 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++;
    }

一直在寻找一段时间,并认为它需要一双新的眼睛......有什么想法吗?

【问题讨论】:

  • 发布您的 logcat 错误。
  • 我立即看到的内容:if(cursor != null && cursor.moveToFirst()) 这会将光标移动到循环的每次迭代中的第一个条目......并且:如果标题超过 100 个怎么办?
  • java.lang.ArrayIndexOutOfBoundsException at com.example.dbHelper.getTitles(dbHelper.java:171) --- 那就是 titleArray[i] = title;行
  • btn.setText(titlesArray[i]); 应该是btn.setText(titles); 吗?

标签: java android arrays indexoutofboundsexception


【解决方案1】:

如果您的查询返回超过 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);       
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多