Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQL - Check if whole row already exists in database

I'm trying to create a simple favorites application, where you can keep your favorites pages (from the web for example).

Let's say I have the following data in my database

Title    | URL     | TAG      |
-------------------------------
Hey       Ho.com    Site
Jo        Jo.com    Image
Jo        Mo.com    Image

Now I want to make sure, the user does not add the same page twice, so I will check if the value already exists. But I need to that the user does not add a site to the table that has already been added.

So let's say I would try to add:

Title    | URL     | TAG      |
-------------------------------
Jo        Mo.com    Image

This it would return true (for "check if row exist", because an identical row already exists).

But if I would try to add:

Title    | URL     | TAG      |
-------------------------------
Jo        Go.com    Image

It would return false (though the title already exists), because there is no identical row.

This is the code where I add my data to the database with:

public long createNote(String title, String url, String rn) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_TITLE, title);
    initialValues.put(KEY_URL, url);
    initialValues.put(KEY_RN, rn);

    return mDb.insert(DATABASE_TABLE, null, initialValues);

How can I check if a row already exists in a database?

like image 392
Mdlc Avatar asked Dec 19 '13 16:12

Mdlc


1 Answers

You can check using cursor:

public boolean checkEvent(String title, String URL, String tag) 
{
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLES, 
            new String[] { KEY_TITLE,KEY_URL,KEY_TAG }, 
            KEY_TITLE + " = ? and "+ KEY_URL + " = ? and " + KEY_TAG + " = ?" , 
            new String[] {title,url,tag}, 
            null, null, null, null);

    if(cursor.moveToFirst())

     return true; //row exists
    else 
     return false;

}

Edit: Code now copy & paste ready

like image 103
Aniket Gupte Avatar answered Oct 04 '22 08:10

Aniket Gupte