Search code examples
javaandroidsqliteandroid-cursor

CursorIndexOutOfBoundException index 0 size 0 in android


I'm trying to implement a feature in my app where a SOS button will be displayed in the login screen if the user has logged in before. If not, the SOS button will not be displayed.

For this, I have created a database table in SQLite solely for tracking whether the user has logged in before or not. Whenever the user logs in, a string value LoggedIn will be inserted in the table.

While loading the login page, the data for login status is fetched from the database table. If the data is LoggedIn, I'm displaying the SOS button, otherwise, I'm making the SOS button invisible.

I am using the following method to get the status data, but I'm getting an exception:

CursorIndexOutOfBoundException index 0 size 0

 public String getLoggedInStatus()
    {
        SQLiteDatabase db = getReadableDatabase();
        String status="";
        String query = "SELECT * FROM  LoggedInStatus";   //LoggedInStatus is my table to store login status

        Cursor  cursor = db.rawQuery(query,null);

        if (cursor != null) {
          cursor.moveToFirst();
          status = cursor.getString(0); 
          //Exception is occuring in the above line
        }

        return status;
    }

How do I fix this? How do I read data from the cursor correctly?


Solution

  • The message is saying that you are trying to read (extract data) from the first column of the first row BUT that there is no first row and thus that index 0 (row 1) is out of bounds (column 0 would always exist as otherwise the query would be invalid and fail with another message (probably a syntax error)).

    The reason being that no rows have been returned. Checking for a null Cursor from the rawQuery method (or the equivalent query convenience method) is useless as a Cursor will be returned. However, if the Cursor has no rows it will be empty and thus the getCount method would return 0 .

    The Cursor's move???? methods (such as moveToFirst) will also return false if the move cannot be made.

    As such you could, instead of using if (cursor != null) {........}, use if (cursor.moveToFirst()) { ...... } or if (cursor.getCount() > 0) {......}.

    As such the following would fix the issue :-

    public String getLoggedInStatus()
    {
        SQLiteDatabase db = getReadableDatabase();
        String status="";
        String query = "SELECT * FROM  LoggedInStatus";   //LoggedInStatus is my table to store login status
    
        Cursor  cursor = db.rawQuery(query,null);
    
        if (cursor.moveToFirst) { //<<<<<<<<<< CHANGED
            cursor.moveToFirst();
            status = cursor.getString(0); 
        }
        cursor.close() //<<<<<<<<<< You should always close cursors when done with them
        return status;
    }
    
    • Note in the case that there are no rows to be returned getLoggedInStatus method will return an empty string.