Trying to update values of an SQLite database from an Android app - android

Using the following code I can't upgrade the data in the database:
public void modification(int pos) {
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,
"administracion", null, 1);
SQLiteDatabase db = admin.getWritableDatabase();
ContentValues record = new ContentValues();
record.put(AdminSQLiteOpenHelper.ALARM_HOUR, alarmList.get(pos).getHour());
record.put(AdminSQLiteOpenHelper.ALARM_DATE, alarmList.get(pos).getDate());
record.put(AdminSQLiteOpenHelper.ALARM_ACTIVE, 1);
int numOfRows = db.update("alarm", record, "id=" + alarmList.get(pos).getId(), null);
db.close();
}
The method update is returning 0 when it should return the number of rows affected and I have already checked that the id I put in the method exists in the database. It should return 1.
¿Does anyone know where is my mistake?
Thanks in advance

Related

sqlite database overwrites existing record than inserting new record in physical device

I am facing challenge where i am unable to insert new record into table, rather it overwrites the first record in the table.
This happens in the physical device where as it is working fine in the emulator.
Following is the code used to insert the record:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss", Locale.getDefault());
String strDate = formatter.format(date);
//SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING);
SQLiteDatabase db = this.getWritableDatabase();
/*ContentValues values = new ContentValues();
//values.put("UserId",1);
values.put("NoQPassed", scoreValues.get("NoPassed"));
values.put("NoQFailed", scoreValues.get("NoFailed"));
values.put("NoQSkipped", scoreValues.get("NoSkipped"));
values.put("SubjectName", scoreValues.get("strSubjectName"));
values.put("CompletedDateTime", strDate);
intRetVal= db.insert(score_Table_Name, null, values);*/
String strQuery="insert into "+score_Table_Name+" values ('"+strDate+"','"+scoreValues.get("NoPassed")+
"','"+scoreValues.get("NoFailed")+"','"+scoreValues.get("NoSkipped")+"','"+scoreValues.get("strSubjectName")+"')";
db.execSQL(strQuery);
db.close();
Tried inserting using db.insert and db.executeSQL, but none help. Can someone help me where i am going wrong?
I didnt add any primary key or autoincrement key to make sure the conflict is not because of that column. Do we always need to have primary key to insert new record?
you can use below getCount() method to count occurrences. if getCount(name)== 0 then do inserting. otherwise not inserting and try to log.
public int getCount(String name) {
Cursor c = null;
try {
db = Dbhelper.getReadableDatabase();
String query = "select count(*) from TableName where name = ?";
c = db.rawQuery(query, new String[] {name});
if (c.moveToFirst()) {
return c.getInt(0);
}
return 0;
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
But this logic may not be valid if you say you override it. I think there is no override possibilities in that android sqlite. Please check you might be drop your database any where before inserting new record. It may seems like override data

how to update a SQQLite database with particular row?

while updating in database, I'm not getting the id of particular row
here is my code for update Note in database
public int updateNote(int id, String tittle, String content , String update_at)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Note.COLUMN_TITTLE,tittle);
values.put(Note.COLUMN_CONTENT,content);
values.put(Note.COLUMN_TITTLE,update_at);
return db.update(Note.TABLE_NAME,values,Note.COLUMN_ID+"="+id,null);
}
Please help me.
update returns the number of rows affected and not the id of the row.
In your case if successful it would return 1.
About the id you need you already have it.
As mTak outlined, the update method returns the number of rows affected. You can also see that in the documentation.
If you want your method to return the ID of the row you updated, then return the id that you pass in, since that's how you select the row to update in the first place:
public int updateNote(int id, String tittle, String content , String update_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Note.COLUMN_TITTLE,tittle);
values.put(Note.COLUMN_CONTENT,content);
values.put(Note.COLUMN_TITTLE,update_at);
db.update(Note.TABLE_NAME,values,Note.COLUMN_ID+"="+id,null);
return id;
}
In your Activity Class:
//*Note is your setterClass
//*notesList is your ArrayList or list
//*position refers your current list position
//*setNote is a method in Note Class
private void updateNote(String note, int position) {
Note n = notesList.get(position);
// updating note text
n.setNote(note);
// updating note in db
db.updateNote(n);
// refreshing the list
notesList.set(position, n);
mAdapter.notifyItemChanged(position);
}
In your database class try below code:
public int updateNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Note.COLUMN_NOTE, note.getNote());
// updating row
return db.update(Note.TABLE_NAME, values, Note.COLUMN_ID + " = ?",
new String[]{String.valueOf(note.getId())});
}
here i am trying to update single string.i hope this is workig to you.Let me know is this working or not.

Updating rows in Android SQlite

I'm using SQlite in my Android app and the task is - how can I update all the rows in one table?
I have a 1st column with name "cl_id" (integer numbers 1-2-3-4..) and after deleting some rows, I wan't to make a cycle to fill this 1st column with a new values to keep them in right order.
I was trying to execute:
data.put("cl_id",index);
db.update("mdb_table_contactList", data, null, null);
but it's updates all the values in the first column :(
To update the field in specific row, try this;
ContentValues data = new ContentValues();
data.put("cl_id",index);
db.update("mdb_table_contactList", data, "id="+_id, null);
db.close();
It's good practice to have a primary key for each row data.
Here _id would be your primary key.
"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);
}
Try this it must work
void updateDatail(String id) {
ContentValues data = new ContentValues();
data.put("cl_id",index);
db.update("mdb_table_contactList", data, "id=?", new String[]{id});
db.close();
}

Record is not getting update in database

I have saved data in database. I am trying to update data.
But record is not getting update.
If I debug the update function it shows the values i have entered. But when I retrieve the data it dose not show updated values.
What's wrong?
update function in helper class
public int updateEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE,event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
values.put(KEY_NOTIFICATION_TIME,event.getNotificationTime());
// updating row
return db.update(TABLE, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.getId()) });
}
updating in activity:
if (editMode) {
eventData.setTitle(title.getText().toString());
eventData.setFromDate(showFromTime.getText().toString());
eventData.setToDate(showToTime.getText().toString());
eventData.setDayOfWeek(selectDay.getText().toString());
eventData.setLocation(mAutocompleteView.getText().toString());
eventData.setNotificationTime(notifyTime.getText().toString());
db.updateEvent(eventData);
}
else {
db.addEvent(new EventData(eventTitle, startTime, endTime, dayOfWeek, location, notificationTime));
}
setResult(RESULT_OK, i);
finish();
}
Thank you..

How to keep the database updated when the user enters new values in android studio?

I'm dealing with a simple app, which basically stores various dates. But when I enter a new date, I have to close the app and open it again. The same thing counts for changing the date values. I can only see the changes by closing the app and reopening it.
Here are the two main functions in my DB class;
public void addBirthday(Person person){ //Add a data to database
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(column_name, person.getName());
cv.put(column_sname, person.getSname());
cv.put(column_day, person.getDay());
cv.put(column_month, person.getMonth());
cv.put(column_year, person.getYear());
db.insert(TABLE_NAME, null, cv);
db.close();
}
public int updateBirthday(Person person) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues cv = new ContentValues();
cv.put(column_name, person.getName());
cv.put(column_sname, person.getSname());
cv.put(column_day, person.getDay());
cv.put(column_month, person.getMonth());
cv.put(column_year, person.getYear());
// 3. updating row
int i = db.update(TABLE_NAME, //table
cv, // column/value
column_id +" = ?", // selections
new String[] { String.valueOf(person.getId()) }); //selection args
// 4. close
db.close();
return i;
}
You will need to refresh the view (probably a ListView) where you display this data.
Get rid of the notifyDataSetChanged() and call requery() on your Cursor

Categories

Resources