Search code examples
javaandroidandroid-studioandroid-sqlite

Sqlite DatabaseHelper. make a return method


How do I make a method in my databaseHelper (that extends from SQLiteOpenHelper) class that returns a string for some data of a user.

For example

public String getUserPassword (String username){

    ..
    return password;
}

I just don't know how to make a Cursor that Search for the username (which is the primary key) and find the same user then return his password.


Solution

  • You can use the method rawQuery() of the SQLiteDatabase class which returns a Cursor.
    For this method you must pass 2 arguments:

    • the sql statement which is a SELECT statement
    • an array containing the username's value which will be used in the WHERE clause to return the password (if it exists).

    This method will return the password or null if the username is not found in the table:

    public String getUserPassword (String username){
        String password = null;
        SQLiteDatabase db = this.getWritableDatabase();
        String sql = "SELECT password FROM tablename WHERE username = ?"; 
        Cursor c = db.rawQuery(sql, new String[] {username});
        if (c.moveToNext()) password = c.getString(0);
        c.close();
        db.close();
        return password;
    }
    

    In this line:

    String sql = "SELECT password FROM tablename WHERE username = ?"; 
    

    change the names of the table and the columns to the names that you have in your database.