简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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