Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if entry exist in a database

Tags:

java

android

sql

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!

like image 488
user1756209 Avatar asked Dec 06 '25 19:12

user1756209


1 Answers

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.

like image 58
Sam Avatar answered Dec 08 '25 09:12

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!