score:317
First make a ContentValues object :
ContentValues cv = new ContentValues();
cv.put("Field1","Bob"); //These Fields should be your String values of actual column names
cv.put("Field2","19");
cv.put("Field2","Male");
Then use the update method, it should work now:
myDB.update(TableName, cv, "_id = ?", new String[]{id});
score:0
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);
}
score:0
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);
}
score:1
just try this way
String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);**
score:1
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);
}
score:1
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)
}
score:1
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
score:1
Here I have completed this kind of code for update the row of a database, this is the code of Database handler class
public Boolean updateData(String id,String name,String age,String gender){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ID,id);
contentValues.put(NAME,name);
contentValues.put(AGE,age);
contentValues.put(GENDER,gender);
sqLiteDatabase.update(TABLE_NAME,contentValues,ID+"= ?",new String[]{id});
return true; //Boolean value return korbe
}
score:2
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}
score:2
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
}
score:2
//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.
score:2
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();
}
score:3
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);
score:5
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();
score:6
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);
score:7
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;
}
score:14
you can try this...
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
score:26
- I personally prefere .update for its convenience. But execsql will work same.
- 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);
score:44
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.
score:54
Simple way:
String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;
myDataBase.execSQL(strSQL);
Source: stackoverflow.com
Related Query
- SQLite in Android How to update a specific row
- Android eclipse Dump SQLite table row into text file
- How to test Android sqlite with junit?
- How do I statically link sqlite to my android application?
- How to update Android jni code changings
- how to run Specific activity in android emulator?
- How to scan all mp3 files and not only from specific path for an android media player I make
- How to update Android in Java Build Path in Eclipse
- How to update to the latest version of Android Support Library in Eclipse?
- Android Eclipse not working after Java Update how do I fix it?
- How to Update Cordova version in Android Studio
- how can i access the Sqlite database on real android device using DDMS in eclipse juno
- How to explore the SQLite db while the app is running? Eclipse (Juno) > Android (adb)
- how to use alarm manager to update service every hour in android
- How to update LibPng in an Android project?
- How to find row number in database using primary key (Android SQLite Eclipse Java)
- How to insert and Retrieve for capture image in android sqlite database
- How to add a specific Google play Services api to Eclipse android project
- How to retrieve image from SQLite database in Android Apps Develoment?
- Android Eclipse How to display specific data from phpMySql database to list view
- How to set up sqlite android database
- How can I find an Eclipse update site of a specific class/package
- How to update sdk in android
- How to return the first row of my SQLite Table in Eclipse
- Android How to slide row when previous row visibility set to Visible?
- How can I update the available Android APIs in Eclipse (ADT)
- Android SQLite Update Method Won't Update
- Android App not crashing when inserting row into SQLite database
- How to keep exisiting sqlite databse in Android and Eclipse??
- How to create camera application with specific object detection on android using eclipse?
More Query from same tag
- javascript onclick not working for android app
- Programmatically start an OSGi folder bundle
- How to make queue value saved/displayed?
- Eclipse Project --> Clean goes forever
- Typo correction in IntelliJ
- The console in Eclipse (Java) does not output things in the correct/chronological order
- Eclipse shows a terribly bad autocompletion when I type "if"
- How to switch bewteen panels in WindowBuilder (Java)
- Error when running JAR file
- Android can't open file for reading in Logcat
- org.hibernate.cfg.beanvalidation.TypeSafeActivator;141) HHH000274: Unable to apply constraints on DDL
- scrollable layout not working
- Eclipse formatter line breaking assignments and method invocations
- java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/faces/FacesException
- Annotation are only available for java 1.5 and greater when generating Google App Engine Backend(JDK 1.8, new ADT installed)
- Connect remote hadoop server using eclipse
- Importing Eclipse Plugin source in Eclipse
- How to retrieve subproperty of a data property in OWL API 4.0
- Not able to validate the plug-in in eclipse
- eclipse PDT: How to enable content/code assist for personal PHP libraries
- GCD input number
- Finding project dependencies in Eclipse
- Access is denied in GAE in Eclipse
- JFrame shows up empty on Java Swing GUI
- How do I clear search results in Eclipse?
- ECL - showing differences results for debugging
- Cannot run class files compiled by eclipse in command line
- Calling a web method from eclipse using KSOAP2
- How to use jacoco manually in eclipse gradle project
- Running TestNG programmatically need loop to create multiple tests automatically