Android SQLite Update Column - android

User Case :
Select item by id, if its already present in the basket.
Check the numbers of this item.
If item numbers == 1 then delete this item from basket table and return 0.
If its greater than 1 then decrement it by one and update the table and return number-- .
Its not updating my "numbers" column, and silently passes through the execution and I am helpless nor can I post any stack trace here, but I am posting my code fragment, responsible for this job.
public int removeFromBasketasAnonymous(Long _id){
Log.d("app : ", " _id = " + _id);
int numbers = 0;
try {
database = openDatabaseInReadMode();
Cursor cursor = database.rawQuery("select * from basket where basket._id=" + _id + ";", null);
if (cursor != null) {
cursor.moveToFirst();
Log.d(APP, "GetCount = " + cursor.getCount());
if (cursor.getCount() == 1) {
//this item already present in basket
numbers = cursor.getInt(1);
Log.d(APP, " numbers = " + numbers);
Log.d(APP, "db id = " + cursor.getString(0));
String[] columns = cursor.getColumnNames();
for(String str : columns){
Log.d("APP ", " columns = "+str);
}
Log.d(APP, " id = " + _id);
if (numbers == 1) {
//remove this row entry
cursor.close();
database.close();
database = openDatabaseInReadWriteMode();
database.beginTransaction();
String strSQL = "DELETE from basket where basket._id=" + _id;
try{
database.execSQL(strSQL);
}catch(Exception e){
e.printStackTrace();
}finally{
database.endTransaction();
database.close();
}
numbers--;
} else {
//decrement this number by one
Log.d(APP, " number " + numbers);
numbers--;
Log.d(APP, " dcremented numbers = " + numbers);
cursor.close();
database.close();
database = openDatabaseInReadWriteMode();
database.beginTransaction();
try{
ContentValues data = new ContentValues();
data.put("numbers", numbers);
database.update("basket", data, "_id = " + _id, null);
}catch (Exception e){
e.printStackTrace();
}finally {
database.endTransaction();
database.close();
}
}
}
}
}finally{
if(database != null){
database.close();
}
}
return numbers;
}
public SQLiteDatabase openDatabaseInReadMode() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!isDataBaseExist()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
/*Log.d("DB available", "path = " + dbFile.exists() + " path" + dbFile.getPath());*/
/*Log.d("actual path ", "exists = " + isDataBaseExist());*/
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
public SQLiteDatabase openDatabaseInReadWriteMode() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!isDataBaseExist()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
/*Log.d("DB available", "path = " + dbFile.exists() + " path" + dbFile.getPath());*/
/*Log.d("actual path ", "exists = " + isDataBaseExist());*/
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
}
Regards,
Shashank

How you can use database transaction in Android
If you want to start the transaction there is a method beginTransaction()
If you want to commit the transaction there is a
method setTransactionSuccessful() which will commit the values in the
database
If you had start the transaction you need to close the transaction so there is a method endTransaction() which will end your database transaction
Now there are two main points
If you want to set transaction successful you need to write
setTransactionSuccessful() and then endTransaction() after
beginTransaction()
If you want to rollback your transaction then you need to endTransaction()
without committing the transaction by setTransactionSuccessful().

Related

Want to create,update and retrieve data from SqLite

For Create table :
private static void createAllTables(SQLiteDatabase database) {
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID + " REAL NOT NULL" +"," + TOTAL_DISPLACEMENT_DISTANCE + " REAL NOT NULL" + "" + ");");
}
for Update table, want to save only displacement so i update every time because i want to override the data.
public void insertTotalDisplacement(String userID, Double displacement) {
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, userID); //User phone No used as a USER ID
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.update(NewDatabaseForInRideData.IN_RIDE_DATA,contentValues, NewDatabaseForInRideData.USER_ID+" = "+userID, new String [] {});
} catch (Exception e) {
e.printStackTrace();
}
}
For Retrieving data, I used several ways to do this but data not save in database and not retrieved from database.
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
// cursor = database.rawQuery(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
//choice = String.valueOf(cursor.getDouble(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE)));
Cursor cur=database.rawQuery("SELECT "+NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE+" where "+NewDatabaseForInRideData.USER_ID+" = " +1+ " from"+NewDatabaseForInRideData.IN_RIDE_DATA,new String [] {});
//Cursor cur=database.rawQuery("SELECT * from IN_RIDE_DATA",new String [] {});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
The issue is in getTotalDisplacementDistance method, you are using two cursor variables, one has query result and other is null, and you are processing the one with null value.
Update it accordingly,
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
cursor = database.rawQuery("SELECT " + NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE + " from IN_RIDE_DATA where " + NewDatabaseForInRideData.USER_ID + " = ?", new String[] {"1"});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
You can try this
String selectQuery = "SELECT * FROM " + IN_RIDE_DATA;
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.USER_ID))));
contact.setName(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE))));
// Adding data to your list
list.add(contact);
} while (cursor.moveToNext());
db.setTransactionSuccessful();
}
db.endTransaction();
Edit
Use you model class for setting data
I change these things
For Creating Table
private static void createAllTables(SQLiteDatabase database) {
//database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID +"," + TOTAL_DISPLACEMENT_DISTANCE + "" + ");");
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " ("
+ TOTAL_DISPLACEMENT_DISTANCE + " TEXT, "
+ USER_ID + " TEXT"+");");
}
For Deleting Table
public void deleteDriverLocData() {
try {
database.delete(NewDatabaseForInRideData.IN_RIDE_DATA, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
For Inserting
public void insertDisplacement(String id, String displacement) {
try {
deleteDriverLocData();
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
}
For retrieving the values:
public String getDisplacement() {
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
Cursor cursor = database.query(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
cursor.moveToFirst();
String totaldisplacement = cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE));
return totaldisplacement;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}

Android sqlite id missing after update

after I update an object in my syncAdapter I can't get it back by id again. It seems that the id get lost after the update. What leaves behind is a null object.
Here's my source code how I update the object:
#Override
public void updateUserThread(Context ctxt, UserThread userThread, boolean notified)
{
try
{
ContentValues values = new ContentValues();
values.put(DBHandler.TOPIC, userThread.getTopic());
if(userThread.getCreationDate() != null)
values.put(DBHandler.USER_THREAD_CREATION_DATE, userThread.getCreationDate().getTime());
values.put(DBHandler.THREAD_TYPE, Helper.threadTypeToString(userThread.getThreadType()));
values.put(DBHandler.MEETING_PLACE, userThread.getMeetingPlace());
values.put(DBHandler.SUBJECT, userThread.getSubject());
values.put(DBHandler.SENT, Helper.convertBooleanToInt(userThread.isSent()));
if(userThread.getStartDate() != null)
values.put(DBHandler.START_DATE, userThread.getStartDate().getTime()); //Helper.getDateTime(
values.put(DBHandler.FOR_ALL, userThread.isForAll());
values.put(DBHandler.ID_SERVER, userThread.getIdServer());
if(userThread.getAuthor() != null)
values.put(DBHandler.ID_USER_FK, userThread.getAuthor().getIdUser());
if(notified)
{
ctxt.getContentResolver().update(TeamChannelProvider.USER_THREAD_URI, values, DBHandler.ID_USER_THREAD + "=" + "?", new String[]{String.valueOf(userThread.getIdUserThread())});
}
else
{
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
long status = db.update(TABLE_USER_THREAD, values, DBHandler.ID_USER_THREAD + "=?", new String[]{String.valueOf(userThread.getIdUserThread())});
db.setTransactionSuccessful();
db.endTransaction();
Log.i(Constants.TAG, "Status: " + status);
}
}
catch(Exception exc)
{
Log.e(Constants.TAG, "ERROR - DBHandlerTeamChannel -> updateUserThread", exc);
}
finally
{
Log.i(Constants.TAG, "UserThread updated with ID " + (notified ? "(notified) " : "not notified ") + userThread.getIdUserThread() + ", Server-ID: " + userThread.getIdServer());
}
}

How to delete a row from sqlite table in recycler view items in Android?

I am trying to delete a row in sqlite database from recyclerview adapter. Based on the position of the adapter, I am deleting my row in sqlite like this :
helper = new DBHelper(v.getContext());
database = helper.getWritableDatabase();
//statement = database.compileStatement("update result set ANS =? where SNO ='" + pos + "'");
// statement = database.compileStatement("delete result where SNO ='" + pos + "'");
//statement.bindString(1, ANS);
// statement.executeInsert();
database.delete("result",
"SNO = ? ",
new String[]{Integer.toString(pos)});
Log.d("pos", "" + pos);
// helper.Delete(pos);
database.close();
but it is not deleting in my table, and I am not getting any error. What am I doing wrong?
db = this.getWritableDatabase();
int l;
l = db.delete("result", SNO = ? " , new String[]{pos+1});
if (l > 0) {
Toast.makeText(context, "Removed "+(pos+1), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
db.close();
Here you have pass "pos" so you have not passed right SNO(pos).
Please check SNO is passes on delete query
Try this method ,
public int deleteItem(String id) {
open();
int b = 0;
try {
b = db.delete(DATABASE_TABLE_POST_ITEMS, TAG_PLUS + " = '" + id + "'", null);
} catch (Exception e) {
e.printStackTrace();
}
close();
return b;
}
call this by using this sentence,
holder.img_plus.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dbhelper.deleteItem((chatMessageList.get((int) v.getTag()).getListid()));
chatMessageList.remove(position);
notifyDataSetChanged();
}
});

Database is not retrieving all rows instead getting only unique rows

I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.

android - cannot delete a record in the database

I have a function that should delete a record in my sqlite database. But it is not deleting, what could be wrong?
public boolean deleteLoc(String id) {
boolean deleteSuccessful = false;
try {
SQLiteDatabase db = this.getWritableDatabase();
deleteSuccessful = db.delete(TABLE_NAME, "id =" + id, null) > 0;
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return deleteSuccessful;
}
it always returns false.
try out this:
deleteSuccessful = db.delete(TABLE_NAME, "id ='" + id + "'", null) > 0;
otherwise there is no corresponding record in table.......have you checked your table for the entry you are trying to delete?
If id is of type string then, you should use:
deleteSuccessful = db.delete(TABLE_NAME, "id ='" + id + "'", null) > 0;
EDIT:
If id is of type Numeric then, you should convert it to long:
long longId = Long.parseLong(id);
deleteSuccessful = db.delete(TABLE_NAME, "id =" + longId, null) > 0;

Categories

Resources