[java] SQLite in Android How to update a specific row

I've been trying to update a specific row for a while now, and it seems that there are two ways to do this. From what I've read and tried, you can just use the:

execSQL(String sql) method

or the:

update(String table, ContentValues values, String whereClause, String[] whereArgs) method.

(Let me know if this is incorrect as I am new to android and very new to SQL.)

So let me get to my actual code.

myDB.update(TableName, "(Field1, Field2, Field3)" + " VALUES ('Bob', 19, 'Male')", "where _id = 1", null);

I am trying to accomplish this:

Update Field1, Field2, and Field3 where the primary key (_id) is equal to 1.

Eclipse gives me a red line right underneath the word "update" and gives me this explanation:

The method update(String, ContentValues, String, String[]) in the type SQLiteDatabase is not applicable for the arguments (String, String, String, null)

I'm guessing I'm not assigning the ContentValues correctly. Can anyone point me in the right direction?

This question is related to java android sql eclipse sqlite

The answer is


At first create a ContentValues object :

ContentValues cv = new ContentValues();
cv.put("Field1","Bob");
cv.put("Field2","19");

Then use the update method. Note, the third argument is the where clause. The "?" is a placeholder. It will be replaced with the fourth argument (id)

myDB.update(MY_TABLE_NAME, cv, "_id = ?", new String[]{id});

This is the cleanest solution to update a specific row.


Simple way:

String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;

myDataBase.execSQL(strSQL);

SQLiteDatabase myDB = this.getWritableDatabase();

ContentValues cv = new ContentValues();
cv.put(key1,value1);    
cv.put(key2,value2); /*All values are your updated values, here you are 
                       putting these values in a ContentValues object */
..................
..................

int val=myDB.update(TableName, cv, key_name +"=?", new String[]{value});

if(val>0)
 //Successfully Updated
else
 //Updation failed

you can try this...

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

use this code in your DB `

public boolean updatedetails(long rowId,String name, String address)
      {
       ContentValues args = new ContentValues();
       args.put(KEY_ROWID, rowId);          
       args.put(KEY_NAME, name);
       args.put(KEY_ADDRESS, address);
       int i =  mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
    return i > 0;
     }

for updating in your sample.java use this code

  //DB.open();

        try{
              //capture the data from UI
              String name = ((EditText)findViewById(R.id.name)).getText().toString().trim();
              String address =(EditText)findViewById(R.id.address)).getText().toString().trim();

              //open Db
              pdb.open();

              //Save into DBS
              pdb.updatedetails(RowId, name, address);
              Toast.makeText(this, "Modified Successfully", Toast.LENGTH_SHORT).show();
              pdb.close();
              startActivity(new Intent(this, sample.class));
              finish();
        }catch (Exception e) {
            Log.e(TAG_AVV, "errorrrrr !!");
            e.printStackTrace();
        }
    pdb.close();

  1. I personally prefere .update for its convenience. But execsql will work same.
  2. You are right with your guess that the problem is your content values. You should create a ContentValue Object and put the values for your database row there.

This code should fix your example:

 ContentValues data=new ContentValues();
 data.put("Field1","bob");
 data.put("Field2",19);
 data.put("Field3","male");
 DB.update(Tablename, data, "_id=" + id, null);

just give rowId and type of data that is going to be update in ContentValues.

public void updateStatus(String id , int status){

SQLiteDatabase db = this.getWritableDatabase();

ContentValues data = new ContentValues();

data.put("status", status);

db.update(TableName, data, "columnName" + " = "+id , null);

}


hope this'll help you:

public boolean updatedetails(long rowId, String address)
  {
     SQLiteDatabase mDb= this.getWritableDatabase();
   ContentValues args = new ContentValues();
   args.put(KEY_ROWID, rowId);          
   args.put(KEY_ADDRESS, address);
  return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)>0;   
 }

 public void updateRecord(ContactModel contact) {
    database = this.getReadableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
    contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
    contentValues.put(COLUMN_NUMBER,contact.getNumber());
    contentValues.put(COLUMN_BALANCE,contact.getBalance());
    database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?", new String[]{contact.getID()});
    database.close();
}

Method for updation in SQLite:

public void updateMethod(String name, String updatename){
    String query="update students set email = ? where name = ?";
    String[] selections={updatename, name};
    Cursor cursor=db.rawQuery(query, selections);
}

public long fillDataTempo(String table){
    String[] table = new String[1];
    tabela[0] = table; 
    ContentValues args = new ContentValues();
    args.put(DBOpenHelper.DATA_HORA, new Date().toString());
    args.put(DBOpenHelper.NOME_TABELA, nome_tabela);
    return db.update(DATABASE_TABLE, args, STRING + " LIKE ?" ,tabela);
}

You try this one update method in SQLite

int id;
ContentValues con = new ContentValues();
con.put(TITLE, title);
con.put(AREA, area);
con.put(DESCR, desc);
con.put(TAG, tag);
myDataBase.update(TABLE, con, KEY_ID + "=" + id,null);

just try this way

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

For updates, need to call setTransactionSuccessfull for changes to get committed like so:

db.beginTransaction();
try {
    db.update(...) 
    db.setTransactionSuccessfull(); // changes get rolled back if this not called
} finally {
   db.endTransaction(); // commit or rollback
}

Can try like this:

ContentValues values=new ContentValues();
values.put("name","aaa");
values.put("publisher","ppp");
values.put("price","111");

int id=sqdb.update("table_name",values,"bookid='5' and booktype='comic'",null);

I will demonstrate with a complete example

Create your database this way

    import android.content.Context
    import android.database.sqlite.SQLiteDatabase
    import android.database.sqlite.SQLiteOpenHelper

    class DBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
        override fun onCreate(db: SQLiteDatabase) {
            val createProductsTable = ("CREATE TABLE " + Business.TABLE + "("
                    + Business.idKey + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                    + Business.KEY_a + " TEXT, "
                    + Business.KEY_b + " TEXT, "
                    + Business.KEY_c + " TEXT, "
                    + Business.KEY_d + " TEXT, "
                    + Business.KEY_e + " TEXT )")
            db.execSQL(createProductsTable)
        }
        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
            // Drop older table if existed, all data will be gone!!!
            db.execSQL("DROP TABLE IF EXISTS " + Business.TABLE)
            // Create tables again
            onCreate(db)

        }
        companion object {
            //version number to upgrade database version
            //each time if you Add, Edit table, you need to change the
            //version number.
            private val DATABASE_VERSION = 1

            // Database Name
            private val DATABASE_NAME = "business.db"
        }
    }

Then create a class to facilitate CRUD -> Create|Read|Update|Delete

class Business {
    var a: String? = null
    var b: String? = null
    var c: String? = null
    var d: String? = null
    var e: String? = null

    companion object {
        // Labels table name
        const val TABLE = "Business"
        // Labels Table Columns names
        const val rowIdKey = "_id"
        const val idKey = "id"
        const val KEY_a = "a"
        const val KEY_b = "b"
        const val KEY_c = "c"
        const val KEY_d = "d"
        const val KEY_e = "e"
    }
}

Now comes the magic

import android.content.ContentValues
import android.content.Context

    class SQLiteDatabaseCrud(context: Context) {
        private val dbHelper: DBHelper = DBHelper(context)

        fun updateCart(id: Int, mBusiness: Business) {
            val db = dbHelper.writableDatabase
            val valueToChange = mBusiness.e
            val values = ContentValues().apply {
                put(Business.KEY_e, valueToChange)
            }
            db.update(Business.TABLE, values, "id=$id", null)
            db.close() // Closing database connection
        }
    }

you must create your ProductsAdapter which must return a CursorAdapter

So in an activity just call the function like this

internal var cursor: Cursor? = null
internal lateinit var mProductsAdapter: ProductsAdapter

 mSQLiteDatabaseCrud = SQLiteDatabaseCrud(this)
    try {
        val mBusiness = Business()
        mProductsAdapter = ProductsAdapter(this, c = todoCursor, flags = 0)
        lstProducts.adapter = mProductsAdapter


        lstProducts.onItemClickListener = OnItemClickListener { parent, view, position, arg3 ->
                val cur = mProductsAdapter.getItem(position) as Cursor
                cur.moveToPosition(position)
                val id = cur.getInt(cur.getColumnIndexOrThrow(Business.idKey))

                mBusiness.e = "this will replace the 0 in a specific position"
                mSQLiteDatabaseCrud?.updateCart(id ,mBusiness)

            }

        cursor = dataBaseMCRUD!!.productsList
        mProductsAdapter.swapCursor(cursor)
    } catch (e: Exception) {
        Log.d("ExceptionAdapter :",""+e)
    }

enter image description here


//Here is some simple sample code for update

//First declare this

private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;

//initialize the following

dbhelper=new DatabaseAppHelper(this);
        db=dbhelper.getWritableDatabase();

//updation code

 ContentValues values= new ContentValues();
                values.put(DatabaseAppHelper.KEY_PEDNAME, ped_name);
                values.put(DatabaseAppHelper.KEY_PEDPHONE, ped_phone);
                values.put(DatabaseAppHelper.KEY_PEDLOCATION, ped_location);
                values.put(DatabaseAppHelper.KEY_PEDEMAIL, ped_emailid);
                db.update(DatabaseAppHelper.TABLE_NAME, values,  DatabaseAppHelper.KEY_ID + "=" + ?, null);

//put ur id instead of the 'question mark' is a function in my shared preference.


if your sqlite row has a unique id or other equivatent, you can use where clause, like this

update .... where id = {here is your unique row id}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

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 eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

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