Reputation: 575
I want to check if an entry exist in my database.
I've tried:
private void saveIt() {
MenuItem item = menu.findItem(R.id.menu_2);
myDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);
Cursor c = myDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + " WHERE idwp= '" + id + "'", null);
if(c == null)
{
item.setIcon(R.drawable.b);
try {
myDB.execSQL("INSERT INTO "+MY_DATABASE_TABLE+" (titel, extra, html) VALUES ('"+titel.replace("'", "\"")+"','"+extra.replace("'", "\"")+"','"+html.replace("'", "\"")+"');");
}
finally
{
if (myDB != null)
myDB.close();
}
Toast.makeText(getApplicationContext(), "saved", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "already exist", Toast.LENGTH_SHORT).show();
}
myDB.close();
}
But always it says "already exist". I've seen my database. There is no entry where id = xxx
!
Thanks for helping!
UPDATE: I've find a misstake: INSERT INTO ... extra, html, id <- I forget the id!
This is a great community to solve problems!
Upvotes: 3
Views: 2331
Reputation: 14274
Change
Cursor c = myDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + " WHERE idwp= '" + id + "'", null);
if(c == null)
{
to:
Cursor c = myDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + " WHERE idwp= '" + id + "'", null);
if(c.getCount() == 0 )
{
Upvotes: 3
Reputation: 86948
A Cursor won't be null
but it might be empty, you need to use this:
if(c.getCount() > 0) {
Toast.makeText(getApplicationContext(), "already exist", Toast.LENGTH_SHORT).show();
}
else {
// Does not exist!
}
You can also use any of the Cursor#move
methods, since they return true
or false
depending on whether there is valid data in the Cursor.
Upvotes: 6