Android sqlite id missing after update - android

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());
}
}

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 "";
}
}

Get message from SMS content URI where message is not delivered

I am developing a system application in which I have to send a message from device programmatically and delete the message after sending.Everything working properly except below point
If the message sent successfully then I am able to find it from SMS content URI but if the message failures then I am not getting it from Content URI.I am using below code for deleting message
public void deleteTheMessage(Context context, String value) {
Uri uri = Uri.parse("content://sms");
Cursor c = context.getApplicationContext().getContentResolver().query(uri, null, null, null, null);
try {
if (c != null) {
Log.i("deleteTheMessage-->", " count : " + c.getCount());
} else {
Log.i("deleteTheMessage-->", " c null: ");
}
while (c.moveToNext()) {
try {
if (c != null && c.moveToFirst()) {
do {
String address = c.getString(2);
String id = c.getString(0);
long threadId = c.getLong(1);
Log.i("deleteTheMessage-->", " address: " + address + " body: " + "" + " threadId: " + threadId + " id: " + id);
try {
if (address.contains(value)) {
int deltedrowcount = context.getApplicationContext().getContentResolver().delete(uri, "thread_id = " + threadId, null);
if (deltedrowcount != 0) {
Log.i("deleteTheMessage-->", " SMS has Deleted successfully " + deltedrowcount);
}
Log.i("deleteTheMessage-->", " body " + address);
}
} catch (Exception e) {
Log.i("deleteTheMessage-->", "SmsWriteOpUtil Exception in deleting SMS " + e.getMessage());
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.i("deleteTheMessage-->", "c.moveToNext() Exception in deleting SMS" + e.getMessage());
}
}
} catch (Exception e) {
Log.i("deleteTheMessage-->", " try Exception in deleting SMS: " + e.getMessage());
} finally {
c.close();
}
}
I want to delete message address by 11345 Please see below screenshot.
Finally, I got the solution to delete the undelivered message using below code.
long threadId = Telephony.Threads.getOrCreateThreadId(context, phoneNumber);
LogMgr.i("deleteByThreadID-->" + " threadId : " + threadId);
int threadIdDeletedCount = context.getContentResolver().delete(Uri.parse("content://sms"), "thread_id =?", new String[]{String.valueOf(threadId)});
LogMgr.i("deleteByThreadID: --> threadIdDeletedCount " + threadIdDeletedCount);
phoneNumber this the number on which message was sent.

Android SQLite Update Column

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().

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;

Adding custom data to contacts in Android

I want to add custom field to contacts that will tell me if the contact was marked in my aplication or not.
First of all I want to make a function that will set my custom data to contact with given id, but the code that I try to use, don't work properly.
public static final String MIMETYPE_EMPLOYEE = "vnd.android.cursor.item/employee";
public void addEmployee(String id){
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Uri newContactUri = null;
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data._ID + "=?", new String[]{id})
.withValue(ContactsContract.Data.MIMETYPE, MIMETYPE_EMPLOYEE)
.withValue(ContactsContract.Data.DATA1, "yes")
.build());
try{
ContentProviderResult[] res = act.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
if (res!=null && res[0]!=null) {
newContactUri = res[0].uri;
Log.d(LOG_TAG, "URI added contact:"+ newContactUri); //here it says that it's null :(
}
else Log.e(LOG_TAG, "Contact not added.");
} catch (RemoteException e) {
// error
Log.e(LOG_TAG, "Error (1) adding contact.");
newContactUri = null;
} catch (OperationApplicationException e) {
// error
Log.e(LOG_TAG, "Error (2) adding contact.");
newContactUri = null;
}
Log.d(LOG_TAG, "Contact added to system contacts.");
if (newContactUri == null) {
Log.e(LOG_TAG, "Error creating contact");
}
}
I also tried to use Insert instead of update but with Insert my application crashed when I tried to retrieve "newContactUri = res[0].uri;"
I have searched for similar solutions but nothing worked for me :/
Topic linked from MAYUR BHOLA helped, thx.
I'm posting working version of my problem, maybe someone will need this.
public static final String MIMETYPE_EMPLOYEE = "vnd.android.cursor.item/employee";
private void updateEmployee(String id, String value){
try {
ContentValues values = new ContentValues();
values.put(Data.DATA1, value);
int mod = act.getContentResolver().update(
Data.CONTENT_URI,
values,
Data.RAW_CONTACT_ID + "=" + id + " AND "
+ Data.MIMETYPE + "= '"
+ MIMETYPE_EMPLOYEE + "'", null);
if (mod == 0) {
values.put(Data.RAW_CONTACT_ID, id);
values.put(Data.MIMETYPE, MIMETYPE_EMPLOYEE);
act.getContentResolver().insert(Data.CONTENT_URI, values);
Log.v(LOG_TAG, "data inserted");
} else {
Log.v(LOG_TAG, "data updated");
}
} catch (Exception e) {
Log.v(LOG_TAG, "failed");
}
}

Categories

Resources