I have a small problem with the method db.update. I need to change a string that corresponds to that received by the query. For example from the query I get the string "hello", if the change in "hello1" must change all the strings "hello".
In my Cursor I have name_s = c.getString(3);
And this is my update:
cv.put(Table1.ABC, Ecia.getText().toString());
db.update(Table1.TABLE_NAME, cv, Table1.ABC+ " = ?", new String[] { name_s});
try this :
String newval=Ecia.getText().toString();
String name_s = c.getString(3);
setMyField(name_s , newval);
public int setMyField(String currvalue , String newvalue) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Table1.ABC, newvalue);
// updating row
return db.update(Table1.TABLE_NAME, values, Table1.ABC + " = ?",
new String[] { currvalue });
}
Related
I am wondering if its possible to query existing database and detect if same value is in the database when inserting.
This is method of inserting in a class extends SQLiteOpenHelper
public void insertTimeTable_Schedule(String title, String subtitle, String color_text, String color_text_bg,
String mon, String tue, String wed, String thus, String fri, String sat, String sun,
String start_time, String end_time){
sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE,title);
values.put(COLUMN_SUBTITLE,subtitle);
values.put(COLUMN_COLOR_TEXT,color_text);
values.put(COLUMN_COLOR_TEXT_BG,color_text_bg);
values.put(COLUMN_MON,mon);
values.put(COLUMN_TUE,tue);
values.put(COLUMN_WED,wed);
values.put(COLUMN_THUS,thus);
values.put(COLUMN_FRI,fri);
values.put(COLUMN_SAT,sat);
values.put(COLUMN_SUN,sun);
values.put(COLUMN_START_TIME,start_time);
values.put(COLUMN_END_TIME,end_time);
sqLiteDatabase.insert(TABLE_TIMETABLE, null, values);
}
Now I'd like to detect and make error message if there is same start_time in COLUMN_START_TIME when inserting new table data.
I tried to display values from database using method will be indicated below, and this will show everything I inserted
public String getData_database(){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{KEY_ID, COLUMN_TITLE,COLUMN_SUBTITLE,COLUMN_COLOR_TEXT,COLUMN_COLOR_TEXT_BG,
COLUMN_MON,COLUMN_TUE, COLUMN_WED,COLUMN_THUS, COLUMN_FRI,COLUMN_SAT,COLUMN_SUN,
COLUMN_START_TIME,COLUMN_END_TIME};
#SuppressLint("Recycle")
Cursor cursor =
sqLiteDatabase.query(TABLE_TIMETABLE,columns,null,null,null,null,null);
int iId = cursor.getColumnIndex(KEY_ID);
int iTitle = cursor.getColumnIndex(COLUMN_TITLE);
int iTextcolor = cursor.getColumnIndex(COLUMN_COLOR_TEXT);
int iTextBgcolor = cursor.getColumnIndex(COLUMN_COLOR_TEXT_BG);
int iSubtitle = cursor.getColumnIndex(COLUMN_SUBTITLE);
int iStarttime = cursor.getColumnIndex(COLUMN_START_TIME);
int iEndtime = cursor.getColumnIndex(COLUMN_END_TIME);
StringBuilder result = new StringBuilder();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.append("Id: ").append(cursor.getString(iId)).append("\n").append("Title: ").append(cursor.getString(iTitle)).append("\n").append("SubTitle: ").append(cursor.getString(iSubtitle)).append("\n").append("Text Color: ").append(cursor.getString(iTextcolor)).append("\n").append("Text BG Color: ").append(cursor.getString(iTextBgcolor)).append("\n").append("Start Time: ").append(cursor.getString(iStarttime)).append("\n").append("End Time: ").append(cursor.getString(iEndtime)).append("\n\n");
}
sqLiteDatabase.close();
return result.toString();
}
If you have any advice, I'd love to hear.
You can have a method that returns a boolean after querying the table. Then in your insert statement you check if the response is true, then show whatever error, otherwise, insert the record.
This method:
public boolean existsStartTime(String start_time){
sqLiteDatabase = this.getWritableDatabase();
String sql = "SELECT 1 FROM " + TABLE_TIMETABLE + " WHERE " + COLUMN_START_TIME + " = ?";
Cursor c = sqLiteDatabase.rawQuery(sql, new String[] {start_time});
boolean result = c.moveToFirst();
c.close();
sqLiteDatabase.close();
return result;
}
will return true if the value of the variable start_time exists in the table or false if it does not exist.
You can check it like:
String start_time = "<value here>";
if (existsStartTime(start_time)) {
<error message here>
} else {
insertTimeTable_Schedule(...);
}
If I use the following code
public boolean updateContact(Integer id, String name, String surname, byte[] image)throws SQLiteException
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("MyName", name);
contentValues.put("MySurname", surname);
contentValues.put("Photo", image);
db.update("details", contentValues, "_id = ? ", new String[] { Integer.toString(id) } );
return true;
}
then If I ommit to add one column it saves null values , How I can create an update only with those fields that are not empty?
Is it possible to add
db.update("details", contentValues, "_id = ? OR name=? OR surname=? ", new String[] { Integer.toString(id) } );
thank you
Is there any variable that is always set, like id? If so, you just have to check variables name and surname against null before adding them to contentValues:
if (name != null && !name.isEmpty()) {
contentValues.put("MyName", name);
}
I want to update my database table with multiple where conditions. I already did with single where condition
db.update(TABLE_MISSING_ITEMS, values, KEY_AUTHOR + " = ?",
new String[] { String.valueOf(items.getAuthor()) });
Now i want 2 where condition.
P.S :- No raw query
You can separate the different WHERE conditions with ANDlike this:
db.update(TABLE_NAME,
contentValues,
NAME + " = ? AND " + LASTNAME + " = ?",
new String[]{"Manas", "Bajaj"});
The way I solved my need
public boolean checkHususiKayit(String baslik, String tarih) {
boolean varMi = false;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_BASLIK,
DBHelper.COLUMN_H_TARIH,
DBHelper.COLUMN_H_YOK_TUR,
DBHelper.COLUMN_H_AD,
DBHelper.COLUMN_H_WEB_ID,
DBHelper.COLUMN_H_NUMARA,
DBHelper.COLUMN_H_YURD_ID,
DBHelper.COLUMN_H_YETKILI_AD,
DBHelper.COLUMN_H_YETKILI_ID,
DBHelper.COLUMN_H_TEL,
DBHelper.COLUMN_H_EMAIL,
DBHelper.COLUMN_H_ADDRESS,
DBHelper.COLUMN_H_VAR,
DBHelper.COLUMN_H_GOREVLI,
DBHelper.COLUMN_H_YOK,
DBHelper.COLUMN_H_IZINLI,
DBHelper.COLUMN_H_HATIMDE};
String whereClause = DBHelper.COLUMN_H_BASLIK + " = ? AND " + DBHelper.COLUMN_H_TARIH + " = ?"; // HERE ARE OUR CONDITONS STARTS
String[] whereArgs = {baslik, tarih};
Cursor cursor = database.query(DBHelper.TABLE_NAME_HUSUSI, kolonlar, whereClause, whereArgs, null, null, null + " ASC");
while (cursor.moveToNext()) {
varMi = true;
}
database.close();
cursor.close();
return varMi;
}
THIS CAN ALSO BE DONE LIKE THIS
public void UpdateData(int Cid,int flag,String username,String password)
{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Status",flag);//I am updating flag here
database.update(TABLE_NAME, cv, ""+KEY_UserName+"= '"+ username+"' AND "+KEY_CID+"='"+Cid+"' AND "+KEY_Password+"='"+password+"'" , null);
database.close();
}
Try this simple query
db.update(TABLE_FF_CHECKLIST_DATA,contentValues, "FFCHECKLISTID = ? and TASK_ID_CHK = ?" , new String[] {"EHS" , "CTO914"});
where "EHS" is value in column FFCHECKLISTID and CTO914 is value in TASK_ID_CHK.
I am Creating DB with three fields name,id,mark. I created table and inserted values using
StudentDb.addStudentDetail(new StudentDetails(id,Name,0));
I used Update method Like:
public int updateStudentDetail(StudentDetails student) {
SQLiteDatabase db = this.getWritableDatabase();`enter code here`
ContentValues values = new ContentValues();
values.put("id", student.getID());
values.put("name", student.getName());
values.put("mark", student.getMark());
int i = db.update(TABLE_STUDENT, values, KEY_ID + " = ?",
new String[] { String.valueOf(student.getId()) });
db.close();
return i;
}
I call this method Like:
StudentDb.updateStudentDetail(student);
I don't know how to pass a value update method?
its very simple. Lets say you want to update the marks of a student. Implement this in your DatabaseHelper class:
public int udpateStudentMarks(final int studentID,final int marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("mark", marks);
int i = db.update(TABLE_STUDENT, values, KEY_ID + " = ?",
new String[] { String.valueOf(studentID) });
db.close();
return i;
}
now you can use it like this:
db.updateStudentMarks(studID,newMarks);
Hope it helps.
I need to update a value in a column from a certain table. I tried this :
public void updateOneColumn(String TABLE_NAME, String Column, String rowId, String ColumnName, String newValue){
String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = "+newValue+" WHERE "+Column+ " = "+rowId;
db.beginTransaction();
SQLiteStatement stmt = db.compileStatement(sql);
try{
stmt.execute();
db.setTransactionSuccessful();
}finally{
db.endTransaction();
}
}
and I call this method like this :
db.updateOneColumn("roadmap", "id_roadmap",id,"sys_roadmap_status_mobile_id", "1");
which means that I want to set the value 1 in the column sys_roadmap_status_mobile_id when id_roadmap = id.
The problem is that nothing happens. Where is my mistake?
Easy solution:
String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = '"+newValue+"' WHERE "+Column+ " = "+rowId;
Better solution:
ContentValues cv = new ContentValues();
cv.put(ColumnName, newValue);
db.update(TABLE_NAME, cv, Column + "= ?", new String[] {rowId});
The below solution works for me for updating single row values:
public long fileHasBeenDownloaded(String fileName)
{
SQLiteDatabase db = this.getWritableDatabase();
long id = 0;
try {
ContentValues cv = new ContentValues();
cv.put(IFD_ISDOWNLOADED, 1);
// The columns for the WHERE clause
String selection = (IFD_FILENAME + " = ?");
// The values for the WHERE clause
String[] selectionArgs = {String.valueOf(InhalerFileDownload.fileName)};
id = db.update(TABLE_INHALER_FILE_DOWNLOAD, cv, selection, selectionArgs);
}
catch (Exception e) {
e.printStackTrace();
}
return id;
}