I have an android studio app that uses sqlite to save user data such as username, password, etc. In the login page after the user enters his login credentials, the user clicks on a button that calls the following function from a DatabaseHelper java class to check if the info is correct:
public boolean checkLogin(String username, String password){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM user WHERE username=? AND password=? ",
new String[] {username, password});
if (cursor.getCount() > 0){
return true;
}
else {
return false;
}
}
I want to save the row ID that matches this user so I can use it in the future and I was thinking of saving the ID into a variable that I will then send to different activities using an intent. The issue is that I can’t figure out how to save the ID from the query.
2
Answers
Basically you just need the
or
to retrieve the data from the columns in the database. I made an example I hope this helps you. I’m not very familiar with programming language some cases so I can’t argue more.
Method to retrieve the Id requested you could just create a String or something..
I’d suggest returning a int rather than boolean the long being the id or -1 if the user/password combination doesn’t exist. So :-
Instead of using something like :-
You could use something like :-
Here’s an example that does that and sends the id to another Activity (NextActivity) and then returns (finishes) from that activity after writing the username and password to the log.
First the Database Helper DBHelper :-
db = this.getWriteableDatabase();
in the constructor.getUserById(ing userId)
method which returns a Cursor according to the userId.MainActivity (a little overly complex as it demonstrates both a failed login attempt (1st) as well as a successful login attempt (as part of handling the failed attempt)) :-
Finally NextActivity :-
Result
When run the log includes :-