简体   繁体   English

字符串数组引发索引超出范围异常

[英]String array throws index out of bounds exception

Im making an android app and this part is where a cursor will go through a database and store the 'title' section of the table into a string array. 我正在制作一个Android应用,这部分是游标将通过数据库并将表的“标题”部分存储到字符串数组中的地方。 This is then called in another class and is used to dynamically show buttons based on the entries. 然后在另一个类中调用它,并根据条目动态显示按钮。 The code for putting the titles into an array is as follows: 将标题放入数组的代码如下:

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;
}

Then it is called with the following code: 然后使用以下代码调用它:

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++;
    }

Been looking for a while and think it needs a fresh pair of eyes.. any ideas? 找了一会儿,认为它需要一双新鲜的眼睛..有什么想法吗?

what if your query returns more than 100 rows? 如果查询返回的行数超过100怎么办? If think it would be safer to use something like 如果认为使用这样的东西会更安全

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++;  
}

of, better, a Collection. 最好是一个集合。

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);       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM