I have those methods
public void insert(ContentValues values){
try {
database = dbhelper.getWritableDatabase();
database.insertOrThrow(dbhelper.TABLE_NAME, null, values);
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
//releasing the resources.
database.close();
dbhelper.close();
}
}
public Cursor query(){
database=dbhelper.getReadableDatabase();
Cursor cur=database.query(DbHelper.TABLE_NAME, null, null, null, null, null, null);
return cur;
}
One inserts data, and another queries data from my db.
Now I insert some data in the db
values = new ContentValues();
values.put("email",email);
values.put("pass",password);
values.put("contact",contact);
DetailsDb detailsDb = new DetailsDb(this);
Cursor cursor = detailsDb.query();
if(cursor.getCount() > 0){
Toast.makeText(this,"Ooops user exists",Toast.LENGTH_SHORT).show();
}else{
detailsDb.insert(values);
Toast.makeText(this,"You are registered",Toast.LENGTH_SHORT).show();
}
Basically, I am saying. If there is a row in the db (cursor.getCount > 0) then the user exists. If not then insert the new user. But if I enter the same user again then, I am getting the " You are registered" message. So something is wrong there. Any ideas?
Thanks,
Theo.
You are rejecting a user if any user exists.
If you want to only reject an already existing user and thus allow multiple users then you need to check if that specific user exists.
So :-
Add a new method :-
public Cursor getUser(String email){
database=dbhelper.getReadableDatabase();
String whereclause = "email=?";
String[] whereargs = new String[]{email};
Cursor cur=database.query(DbHelper.TABLE_NAME, null, whereclause, whereargs, null, null, null);
return cur;
}
this equates to SELECT * FROM your_table WHERE email = the_email_to_check;
as opposed to SELECT * FROM your_table;
Then use :-
values = new ContentValues();
values.put("email",email);
values.put("pass",password);
values.put("contact",contact);
DetailsDb detailsDb = new DetailsDb(this);
Cursor cursor = detailsDb.getUser(email); //<<<<<<
if(cursor.getCount() > 0){
Toast.makeText(this,"Ooops user exists",Toast.LENGTH_SHORT).show();
} else {
if (detailsDb.insert(values) > 0) {
Toast.makeText(this,"You are registered",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Attempt to register unsuccessful",Toast.LENGTH_SHORT).show();
}
}
insert
method returns the rowid of the inserted row which would be 1 or greater if the row was inserted, otherwise it returns -1).