Search code examples
androidandroid-layoutandroid-fragmentsandroid-sqliteandroid-studio-2.0

How to check data in SQLite if already exist update or else insert in android


I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.

Code:

public long  addmenus(String navigationdrawer,String optionname)
    {
        SQLiteDatabase menus=this.getWritableDatabase();
        try {

        ContentValues values=new ContentValues();
        values.put(HEADER_NAME,navigationdrawer);
        values.put(CHILD_NAME,optionname);

       // menus.insert(TABLE_NAME,null,values);
           // String owner=optionname;

            Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);

        if(cursor.getCount()<1)
        {
            //execute insert query here
            long rows = menus.insert(TABLE_NAME, null, values);
            return rows;
            // return rows inserted.
        }
        else
        {
            //Perform the update query
            String strFilter = "CHILD_NAME" + optionname;
            long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
            return updaterow;
            // return rows updated.
        }

       // menus.close();

    } catch (Exception e) {
        return -1;
    }

        finally {
            if (menus != null)
                menus.close();
        }
    }

My activity:

I converted whole json data into string object then insert into SQLite.

  String productpage=jsonObject.toString();
     db.addmenus(productpage,"Navigationmenus");

But It doesn't work.It couldn't insert into sqlite.

Anyone solve this problem Glad to appreciate. Thanks in advance


Solution

  • You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.