Search code examples
androidandroid-sqlitesqliteopenhelper

How can I know my SQLite Table has my desired turple( attribute name )?


I just want to do like that _ I have OrderTable and OrderID, OrderItemQty are save in it. What my problem is , I want to know the order I added is still exist in my database table or not by its OrderID. If I add one order that still exist in my database table, I want to add the new OrderItemQty on that ( existing Order ) or else add new Order.


Solution

  • Method to check if order exists by its Id

    public boolean IsOrderExists(String orderid)
    {
        String selectQuery = "SELECT  * FROM OrderTable  where OrderID = '"+orderid+"' ";
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        cursor.moveToFirst();
        Log.d("Log", "Fetching order from Sqlite: " + cursor.getCount());
    
        if (cursor.getCount() > 0)
        {
            cursor.close();
            db.close();
           return true; //if found return true
        }
        else
        {
            cursor.close();
            db.close();
            return false;// if not return false
        }
    }
    

    in main after initialize db instance do this

    if(IsOrderFound)
    {
        //found update the old qty 
    }
    else
    {
        //not found add new order
    }