Validate Login with Sqlite

Asked

Viewed 1,538 times

1

I have a problem in the logging method, it is logging in with both the right login and password as with them wrong. When it logs in with wrong login the user id goes as 0 and if it logs with the correct data the id will 1 as usual?

    public Usuario validarLogin(String login, String senha) {

    String[] selectionArgs = new String[]{login, senha};
    Cursor cursor;
    cursor = db.rawQuery("select * from usuarios where login=? and senha=?", selectionArgs);
    Usuario usuarioLinha = new Usuario();
    if (cursor.moveToNext()) {
        usuarioLinha.setId(cursor.getLong(cursor.getColumnIndex("id_usuario")));
        usuarioLinha.setEmail(cursor.getString(cursor.getColumnIndex("email")));
        usuarioLinha.setLogin(cursor.getString(cursor.getColumnIndex("login")));
        usuarioLinha.setSenha(cursor.getString(cursor.getColumnIndex("senha")));
    }
    return usuarioLinha;
}
  • 2

    And what was supposed to happen in case of wrong user or password?

1 answer

1

I have no way of knowing which return executed after this code, but is probably checking if the user is different from null, I would make the following change:

Usuario usuarioLinha;
    if (cursor.moveToNext()) {
        usuarioLinha = new Usuario()
        usuarioLinha.setId(cursor.getLong(cursor.getColumnIndex("id_usuario")));
        usuarioLinha.setEmail(cursor.getString(cursor.getColumnIndex("email")));
        usuarioLinha.setLogin(cursor.getString(cursor.getColumnIndex("login")));
        usuarioLinha.setSenha(cursor.getString(cursor.getColumnIndex("senha")));
    }
    return usuarioLinha;

Moving the instantiation inside the cursor, if db does not return anything, the user will be null, so the login is invalid.

  • It worked =D vlwww

Browser other questions tagged

You are not signed in. Login or sign up in order to post.