Hello. There is a database in which records of addresses of sites, passwords and one more thing lie. You need to get this thing if the record with the address and password is available. If not, get an empty string. Wrote a method

public String getSave(String url, String key) { String[] columns = { Database.URL, Database.KEY, Database.SAVE}; String selection = Database.URL + " =?" + " AND " + Database.KEY + " =?"; String[] selectionArgs = { url, key }; Cursor cursor = db.query("save", columns, selection, selectionArgs, null, null, null, "1"); String save; if(!cursor.moveToFirst()){ save = cursor.getString(cursor.getColumnIndex(Database.SAVE); cursor.close(); } else save = ""; return save; } 

I transfer the link and the password to a method. If there are records with such data, then I take a value from Database.SAVE , if not, an empty string. What is wrong? Also the log is strange

 CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 

    1 answer 1

    You have returned an empty cursor. In this case, the condition in the if is incorrectly indicated, which is why the code does not correspond to the description.

    Cursor.moveToFirst returns false if there is no data. Your code in this case is trying to get the value.

    Most likely, it should be the opposite:

     if(cursor.moveToFirst()) { save = cursor.getString(cursor.getColumnIndex(Database.SAVE); } else { save = ""; }