android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

后端 未结 7 2211
甜味超标
甜味超标 2020-11-27 14:14

I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but

相关标签:
7条回答
  • 2020-11-27 14:58

    Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail.

    if( cursor != null && cursor.moveToFirst() ){
        num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
        cursor.close(); 
    }
    

    Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.

    Update Put both the checks in a single statement as mentioned by Jon in the comment below.

    Update 2 Put the close() call within the valid cursor scope.

    0 讨论(0)
  • 2020-11-27 15:02

    try to uninstall the app and then again test it... actually the sqlite db is created only once when the app is first install... so if you think your logic is current then reinstalling the app will do the trick for you. !!!!

    0 讨论(0)
  • 2020-11-27 15:09

    In case people are still looking:

    Instead of searching for "ContactNumber" try searching for Phone.NUMBER. The tutorial has the code with more details: http://developer.android.com/training/basics/intents/result.html

    0 讨论(0)
  • 2020-11-27 15:11

    First check this Condition before fetching data

    if(cursor!=null && cursor.getCount()>0){
      cursor.moveToFirst();
      num = cursor.getString(cursor.getColumnIndex("ContactNumber")); 
    }
    
    0 讨论(0)
  • 2020-11-27 15:17

    Check the return value from moveToFirst(), before you try to read anything from the cursor. It looks as if no results are being returned.

    0 讨论(0)
  • 2020-11-27 15:18

    a save schema to query Cursors is

    // just one
    Cursor cursor = db.query(...);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            value = cursor.getSomething();
        }
        cursor.close();
    }
    
    // multiple columns
    Cursor cursor = db.query(...);
    if (cursor != null) {
        while (cursor.moveToNext()) {
            values.add(cursor.getSomething());
        }
        cursor.close();
    }
    
    0 讨论(0)
提交回复
热议问题