[android] Android SQLite: Update Statement

I need to implement SQLite in my application. I followed this tutorial.. Creating and using databases in Android one

Everything is working fine. I inserted 1 row with 5 columns. Now I want to update value of 1 column only and others will be remain same.

There is one update method in tutorial but it needs all the parameters, however I want to update only one column.

This question is related to android sql sqlite

The answer is


you can always execute SQL.

update [your table] set [your column]=value

for example

update Foo set Bar=125

I use this class to handle database.I hope it will help some one in future.

Happy coding.

public class Database {

private static class DBHelper extends SQLiteOpenHelper {

    /**
     * Database name
     */
    private static final String DB_NAME = "db_name";

    /**
     * Table Names
     */
    public static final String TABLE_CART = "DB_CART";


    /**
     *  Cart Table Columns
     */
    public static final String CART_ID_PK = "_id";// Primary key

    public static final String CART_DISH_NAME = "dish_name";
    public static final String CART_DISH_ID = "menu_item_id";
    public static final String CART_DISH_QTY = "dish_qty";
    public static final String CART_DISH_PRICE = "dish_price";

    /**
     * String to create reservation tabs table
     */
    private final String CREATE_TABLE_CART = "CREATE TABLE IF NOT EXISTS "
            + TABLE_CART + " ( "
            + CART_ID_PK + " INTEGER PRIMARY KEY, "
            + CART_DISH_NAME + " TEXT , "
            + CART_DISH_ID + " TEXT , "
            + CART_DISH_QTY + " TEXT , "
            + CART_DISH_PRICE + " TEXT);";


    public DBHelper(Context context) {
        super(context, DB_NAME, null, 2);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CART);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CART);
        onCreate(db);
    }

}


     /**
      * CART handler
      */
      public static class Cart {


    /**
     * Check if Cart is available or not
     *
     * @param context
     * @return
     */
    public static boolean isCartAvailable(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART;
            Cursor cursor = db.rawQuery(query, null);
            exists = (cursor.getCount() > 0);
            cursor.close();
            db.close();
        } catch (SQLiteException e) {
            db.close();
        }

        return exists;
    }


    /**
     * Insert values in cart table
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean insertItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, "" + itemId);
        values.put(DBHelper.CART_DISH_NAME, "" + dishName);
        values.put(DBHelper.CART_DISH_PRICE, "" + dishPrice);
        values.put(DBHelper.CART_DISH_QTY, "" + dishQty);

        try {
            db.insert(DBHelper.TABLE_CART, null, values);
            db.close();
            return true;
        } catch (SQLiteException e) {
            db.close();
            return false;
        }
    }

    /**
     * Check for specific record by name
     *
     * @param context
     * @param dishName
     * @return
     */
    public static boolean isItemAvailable(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE "
                + DBHelper.CART_DISH_NAME + " = '" + String.valueOf(dishName) + "'";


        try {
            Cursor cursor = db.rawQuery(query, null);

            exists = (cursor.getCount() > 0);
            cursor.close();

        } catch (SQLiteException e) {

            e.printStackTrace();
            db.close();

        }

        return exists;
    }

    /**
     * Update cart item by item name
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean updateItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, itemId);
        values.put(DBHelper.CART_DISH_NAME, dishName);
        values.put(DBHelper.CART_DISH_PRICE, dishPrice);
        values.put(DBHelper.CART_DISH_QTY, dishQty);

        try {

            String[] args = new String[]{dishName};
            db.update(DBHelper.TABLE_CART, values, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();


            return true;
        } catch (SQLiteException e) {
            db.close();

            return false;
        }
    }

    /**
     * Get cart list
     *
     * @param context
     * @return
     */
    public static ArrayList<CartModel> getCartList(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        ArrayList<CartModel> cartList = new ArrayList<>();

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);


            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                cartList.add(new CartModel(
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_ID)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_NAME)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)),
                        Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE)))
                ));
            }

            db.close();

        } catch (SQLiteException e) {
            db.close();
        }
        return cartList;
    }

   /**
     * Get total amount of cart items
     *
     * @param context
     * @return
     */
    public static String getTotalAmount(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        double totalAmount = 0.0;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);


            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                totalAmount = totalAmount + Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) *
                        Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)));
            }

            db.close();


        } catch (SQLiteException e) {
            db.close();
        }


        if (totalAmount == 0.0)
            return "";
        else
            return "" + totalAmount;
    }


    /**
     * Get item quantity
     *
     * @param context
     * @param dishName
     * @return
     */
    public static String getItemQty(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = null;
        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + dishName + "';";
        String quantity = "0";

        try {
            cursor = db.rawQuery(query, null);

            if (cursor.getCount() > 0) {

                cursor.moveToFirst();
                quantity = cursor.getString(cursor
                        .getColumnIndex(DBHelper.CART_DISH_QTY));

                return quantity;
            }


        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        return quantity;
    }


    /**
     * Delete cart item by name
     *
     * @param context
     * @param dishName
     */
    public static void deleteCartItem(Context context, String dishName) {
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        try {

            String[] args = new String[]{dishName};
            db.delete(DBHelper.TABLE_CART, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();
        } catch (SQLiteException e) {
            db.close();
            e.printStackTrace();
        }

    }


}//End of cart class

/**
 * Delete database table
 *
 * @param context
 */
public static void deleteCart(Context context) {
    DBHelper dbHelper = new DBHelper(context);
    SQLiteDatabase db = dbHelper.getReadableDatabase();

    try {

        db.execSQL("DELETE FROM " + DBHelper.TABLE_CART);

    } catch (SQLiteException e) {
        e.printStackTrace();
    }

}

}

Usage:

  if(Database.Cart.isCartAvailable(context)){

       Database.deleteCart(context);

   }

You can try:

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

Or

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

db.update("YOUR_TABLE", newValues, "id=6", null);

Or

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

String[] args = new String[]{"user1", "user2"};
db.update("YOUR_TABLE", newValues, "name=? OR name=?", args);

It's all in the tutorial how to do that:

    ContentValues args = new ContentValues();
    args.put(columnName, newValue);
    db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);

Use ContentValues to set the updated columns and than the update() method in which you have to specifiy, the table and a criteria to only update the rows you want to update.


You can use the code below.

String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);

The SQLiteDatabase object depends on the type of operation on the database.

More information, visit the official website:

https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow

It explains how to manipulate consultations on the SQLite database.

INSERT ROW

Gets the data repository in write mode

SQLiteDatabase db = mDbHelper.getWritableDatabase();

Create a new map of values, where column names are the keys

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

Insert the new row, returning the primary key value of the new row

long newRowId;
newRowId = db.insert(
     FeedEntry.TABLE_NAME,
     FeedEntry.COLUMN_NAME_NULLABLE,
     values);

UPDATE ROW

Define 'where' part of query.

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";

Specify arguments in placeholder order.

String[] selectionArgs = { String.valueOf(rowId) };


SQLiteDatabase db = mDbHelper.getReadableDatabase();

New value for one column

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

Which row to update, based on the ID

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
    int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,
    values,
    selection,
    selectionArgs);

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sqlite

getting " (1) no such column: _id10 " error Laravel: PDOException: could not find driver auto create database in Entity Framework Core How to open .SQLite files Accessing an SQLite Database in Swift When does SQLiteOpenHelper onCreate() / onUpgrade() run? Attempt to write a readonly database - Django w/ SELinux error Android sqlite how to check if a record exists How can I add the sqlite3 module to Python? "Insert if not exists" statement in SQLite