0

I have used following codes to retrieve record:

String getCredentialsFromAdmint(String name ,String pwd) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_ADMIN, new String[] { KEY_ID,
                KEY_A_USER_NAME, KEY_A_PWD }, KEY_A_USER_NAME + "=?" + " AND " + KEY_A_PWD + "=?",
                new String[] { name , pwd }, null, null, null, null);

        if (cursor != null){
            cursor.moveToFirst();
        return cursor.getString(1);
        }
        else{
            return "norecord";
        }

This code works if there is a record but if no record is found then application gets an error. Is there any other ways to retrieve data from database?

3 Answers 3

1

Change your code to following

 if ( cursor.moveToFirst()){
      return cursor.getString(1);
    } else{
        return "norecord";
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You don't check if cursor.moveToFirst() returns true;

It should looks like this:

if (cursor != null) {
   if(cursor.moveToFirst()){
       return cursor.getString(cursor.getColumnIndexOrThrow(KEY_A_USER_NAME));
   } else{
     //no record
   }
} else {
   //invalid uri
}

Comments

0

Try to use the following code instead

if (cursor != null){
    cursor.moveToFirst();
    if(cursor.isAfterLast() == false) {
    return cursor.getString(1);
    }
    else
    {
    return "norecord";
    }
}
else{
    return "norecord";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.