updating method using content values - java

Helper
public boolean mMessagesSent(String ID,int Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, ID);
contentValues.put(KEY_MESSAGES_SENT, Data);
db.update(TABLE_USER_DATA, contentValues, null, null);
return true;
}
Activity
mainData.mTotalMessages("MyData", +1);
mainData.mTotalMessagesSent("MyData",+1);
mainData.mMessages(MessageRecieverId,+1);
mainData.mMessagesSent(MessageRecieverId,+1);
Is this the correct method to update data... I want to increase the int value of data by 1 so i have put +1 but still the value is empty when i retrieve data
CODE AFTER FOLLOWING FIRST ANSWER
public boolean mMessagesSent(String ID,int Data) {
MainData mainData = new MainData(getApplicationContext());
SQLiteDatabase db = mainData.getWritableDatabase();
String newId = ID;
int newData = Data;
MainData helper = new MainData(this); //Change the name to your Helper Class name
Cursor data = helper.getData();
while (data.moveToNext()) {
newId = data.getString(data.getColumnIndex("Data"));
newData = data.getInt(data.getColumnIndex("TotalMessagesSent"));
}
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DATA, newId);
contentValues.put(KEY_MESSAGES_SENT, (newData + 1)); //Change the value of newData(which is actually your old value) by incrementing
db.update(TABLE_USER_DATA, contentValues, null, null);
return true;
}
FETCHING
final MainData myDBHlpr = new MainData(getActivity());
Cursor csr = myDBHlpr.getAllQuestions(getActivity());
while (csr.moveToNext()) {
mTotalMessagesSent.setText(csr.getString(1));
mTotalMessagesRecieved.setText(csr.getString(csr.getColumnIndex("TotalMessagesRecieved")));
mTotalMessages.setText(csr.getString(csr.getColumnIndex("TotalMessages")));
}
csr.close();

Is this the correct method to update data... I want to increase the int value of data by 1 so i have put +1 but still the value is empty when i retrieve data
If you meant to increase the existing value of data by once each time you call the function mMessagesSent()
You can consider to first take the value from the database if it exists, and increment the value. Create a function in Helper as shown below
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
return db.rawQuery(query, null);
}
This will return a Cursor to the Database, to read the values in the database. Do not put the function mMessagesSent in Helper class, put it in the Activity. Now in your mMessagesSent function, call the above function getData() as shown
public void mMessagesSent() {
SQLiteDatabase db = this.getWritableDatabase();
String newId = "default value whatever you have specified";//These two lines may be removed and put outside. If you already have it, then
int newData = 0; //not required to declare here at all, just replace with those variable names
HelperClassName helper = new HelperClassName(this); //Change the name to your Helper Class name
Cursor data = helper.getData();
while(data.moveToNext()){
newId = data.getString(0);
newData = data.getInt(1);
}
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, ID);
contentValues.put(KEY_MESSAGES_SENT, (newData+1)); //Change the value of newData(which is actually your old value) by incrementing
long returnVariable = db.update(TABLE_USER_DATA, contentValues, null, null);
if(returnVariable == -1){
//-1 means there was an error updating the values
}
else{
//the return value if successful will be number of rows affected by the update
}
}
I hope you got your answer.

Related

Why do i get android.database.sqlite.sqlitecursor # error

I get null value whenever I try to display the value of nexpdate. I get the following error android.database.sqlite.sqlitecursor # .
// insertion of values in renew table
public void insertrenew (String rcode, String nexpdate) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("rcode", rcode);
contentValues.put("nexpdate", nexpdate);
db.insert("renew", null, contentValues);
}
//java code to get the value of nexpdate
public String getrenew (String rcode) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT nexpdate from renew where rcode = " + rcode;
String cursor = String.valueOf(db.rawQuery(selectQuery, null));
return cursor;
}
I assume you are getting an error:
android.database.sqlite.sqlitecursor # XXXX // where XXXX indicates object code
Reason/Details:
Reason being here is you are directly casting Cursor object into the String and that's where an issue is!
String cursor = String.valueOf(db.rawQuery(selectQuery, null));
FYI, rawQuery() method actually returns Cursor value and we need to iterate through the cursor actually to get the needed data. You may refer How to retrieve data from cursor class for more details on getting data from the Cursor.

How to use prepared statement for sql?

I'm trying to have an SQLite database in android but I have a problem with that:
I'm trying to update the text value in the "response" column with id 0. The first problem I had was that the string I was using for the update used an apostrophe (') and it had syntax errors because sql closes the string with an '. So I now am using a prepared sql statement for that. The problem now is that the long that is returning gives a -1, so that means that no rows were effected. So how can I update my current string to the row with id=0?
Note: the first string also has an ' but was added using the addData funtion and it didn't give any errors just using db.insert, is that the problem, should I replace all my code with prepared statements?
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public long updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE json_response SET response=? WHERE ID='0'";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, newName); // matches second '?' in sql string
long rowId = statement.executeInsert();
return rowId;
}
I have not used prepared statements much so I can't say why that is not working, but why not use the db.update() method? It takes ContentValues as an argument similar to tour addData() method. Give this a shot.
public int updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("json_response",newName);
int rows = db.update(TABLE_NAME, cv, "ID=0", null);
return rows;
}
[EDIT] update() returns an integer representing the number of rows affected instead of which row was affected. Keep that in mind as your variable name rowId implies that is not what you are looking for.
[EDIT 2] And no, there is no problem with the addData() method that I can see. The apostrophe that was added did not cause an error because ContentValues parameterizes the string values before adding them into the database. Basically, all SQL-like syntax will be ignored when inserting values, which is great for security reasons.
The problem is, I think, that WHERE ID='0' will always fail; what you want is WHERE ID=0

Update multiple rows based on id in sqlite on android?

I have db table as follows
I want to update status column to 1 with id = 1,2,3.
For a single row I can update with content values
public void updateJobStatus(int callId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues data = new ContentValues();
data.put(AppDBConstants.KEY_JOB_DETAIL_STATUS, 1);
db.update(AppDBConstants.TABLE_JOB_DETAIL, data, AppDBConstants.KEY_JOB_DETAIL_CALL_ID + "=" + callId, null);
db.close();
}
What to do for multiple rows?
Update Your query like this
db.update(AppDBConstants.TABLE_JOB_DETAIL, data, AppDBConstants.KEY_JOB_DETAIL_CALL_ID + " IN (?,?,?)", new String[]{"1","2","3"});
I think you current code is working for multiple id but need some of changes as below to achieve your requirement :
public void updateJobStatus(int[] callIds) {
SQLiteDatabase db = this.getWritableDatabase();
if (db != null) {
db.beginTransaction();
try {
for(int id : callIds){
ContentValues data = new ContentValues();
data.put(AppDBConstants.KEY_JOB_DETAIL_STATUS, 1);
db.update(AppDBConstants.TABLE_JOB_DETAIL, data, AppDBConstants.KEY_JOB_DETAIL_CALL_ID + "=" + id, null);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.close();
}
}
Note : As above you need to pass id array it might be one or multiple.
When you have unknown number of arguments, try this one
String args = TextUtils.join(", ", arrayOfIds);
db.execSQL(String.format("UPDATE %s SET %s = true WHERE %s IN (%s);",
TABLE_INCOMING_MESSAGES, KEY_MESSAGE_SENT, KEY_ID, args));

Filter and edit DB row Android studio

I have making project with DB and I have layout with two edittexts in that edittext on activity start I load one column from my DB and display it and in other edittext is text with I want to find specific row in DB table.
When I find that row I need to edit some values in this row. Here is my updatecode in DBadapter.java
// Change an existing row to be equal to new data.
public boolean updateRow(long containercode_row, String lkwnummer,String uniqueid, String containerbarcode,
String timein, String timeout, String howout, String latitudein,
String longitudein, String latitudeout, String longitudeout, String status) {
String where = KEY_CONTAINERBARCODE + "=" + containercode_row;
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_LKWNUMMER, lkwnummer);
newValues.put(KEY_UNIQUEID, uniqueid);
newValues.put(KEY_CONTAINERBARCODE, containerbarcode);
newValues.put(KEY_TIMEIN, timein);
newValues.put(KEY_TIMEOUT, timeout);
newValues.put(KEY_HOWOUT, howout);
newValues.put(KEY_LATITUDEIN, latitudein);
newValues.put(KEY_LONGITUDEIN, longitudein);
newValues.put(KEY_LATITUDEOUT, latitudeout);
newValues.put(KEY_LONGITUDEOUT, longitudeout);
newValues.put(KEY_STATUS, status);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
I need to find row throught KEY_CONTAINERCODE value but I don't know how to make this code in activity where I want to find that row and edit it?
you can update your values by making a method in CommonUtill file like this:
public int updateRecords(String table, ContentValues values,
String whereClause, String[] whereArgs) {
int a = db.update(table, values, whereClause, whereArgs);
return a;
}
there is no need for creating a separate method for this for good practices.

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?
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});
Simple way:
String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;
myDataBase.execSQL(strSQL);
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.
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);
you can try this...
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");
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;
}
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);
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();
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);
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}
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
}
//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.
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();
}
just try this way
String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);**
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);
}
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)
}
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
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
}
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);
}
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);
}

Categories