Database updating but not saving - android

I have an app with a pre-made database. I want to change an entry in this database and save it, but I'm running into some trouble. I have a DatabaseHelper with the following method inside:
public void updateStats(int rowId, int correct, int attempts) {
//Method for updating the stats after a question is answered
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put("CORRECT", correct);
args.put("ATTEMPTS", attempts);
db.update("CHARACTERS", args, "_id=" + rowId, null);
Cursor c = db.query("CHARACTERS", null, null, null, null, null, null);
c.moveToPosition(rowId-1);
Log.d("database", "test - " + String.valueOf(c.getInt(0)));
db.close();
}
It's seems to be running the update fine, because the query is showing that the change has been made in the log. But it's the app is reverting back to the original database when I end the activity.
My knowledge of using databases in Android is patchy, so I'm probably missing something simple. Does anyone know what's going wrong?

please try to use this
ContentValues dataToInsert = new ContentValues();
dataToInsert.put(ALBUM_IS_COMPLETE, "true");
String where = "album_id=?";
String[] whereArgs = {albumid};
try
{
openDataBase();
myDataBase.update(DATABASE_ALBUM_TABLE, dataToInsert, where, whereArgs);
}
catch (Exception e)
{
}
hope this will help you

Related

Edit all the values in a column in SQL

I can't find anything about this on the web.
I need to edit all values in a column in my database but I can't find a way.
I'm doing:
if (upgradeCursor.moveToFirst()){
do {
db.editListsColumn("0");
} while (upgradeCursor.moveToNext());
}
Where upgradeCursor:
return mDb.query(ProductsData.PRODUCTS_TABLE, null, null, null, null, null, null);
And editListsColumn("0"):
public void editListsColumn(String lists) {
mDb=mDbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ProductsMetaData.PRODUCT_PRODUCT, lists);
mDb.update(ProductsData.PRODUCTS_TABLE, cv, "lists=?", null);
}
I'm stuck here.
Any suggestion would be really appreciated at the moment! Thank you so much.
Have you tried a simple update without the where clause and without iterating the cursor. What I mean is simply call this:
mDb=mDbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ProductsMetaData.PRODUCT_PRODUCT, lists);
mDb.update(ProductsData.PRODUCTS_TABLE, cv, null, null);
Without:
if (upgradeCursor.moveToFirst()){
do {
db.editListsColumn("0");
} while (upgradeCursor.moveToNext());
}
From the documentation of the update(String table, ContentValues values, String whereClause, String[] whereArgs) method: passing NULL in whereClause will update all rows.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

How to call Delete method of Database Helper class?

I want to use below given delete method from my Database Helper class. I asked this 2 times but not such responses i am getting. This is the handler class which i had taken from androidhive.info
Delete Method ( In DatabaseHandler File ):
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",new String[] { String.valueOf(contact.getID()) });
db.close();
}
When I am implementing it in another activity. like this:
String a = Integer.toString(_contactlist.get(position).getID());
viewHolder.txtid.setText(a.trim());
viewHolder.txt_name.setText(_contactlist.get(position).getName().trim());
viewHolder.txt_phone.setText(_contactlist.get(position).getPhoneNumber().trim());
final int temp = position;
Contact pm = db.getContact(temp); //temp is the position of the contact
db.deleteContact(pm);
but when I am using this i am getting an unexpected error i.e. it is deleting only 1 data in row not the selected data.
My getContact method :
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
Try giving complete query with where clause. Instead of
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",new String[] { String.valueOf(contact.getID()) });
use
db.execSQL("delete * from TABLE_CONTACTS where KEY_ID = "+contact+";");
Provided, contact should be an integer variable.
but when I am using this i am getting an unexpected error i.e. it is deleting only 1 data in row not the selected data
deleteContact() method will delete only one record from the database as the KEY_ID seems to be unique. Are you expecting more record(s) to be deleted? Or is it deleting wrong record? You may want to put some debug statements in getContact() to check if it retrieving the wrong contact.
I would like to point out a coding problem in getContact() that may not be related to your issue, but still needs to be corrected.
if (cursor != null)
cursor.moveToFirst();
You are checking the null cursor, but there is no guard if it is null and you are still moving ahead to access the cursor. Also you must check null for moveToFirst(), what if the cursor is non-null, but there are no records to read. The app will crash in both cases.
the method deleteContact closes the database handle.

How to check the value already excists or not in sqlite db in android?

In my application I am saving a bill number in SQLite database. Before I add a new bill number how to check if the bill number exists in the DB.
My main class code is,
String bill_no_excist_or_not = db.billno_exist_or_not(""+et_bill_number.getText().toString());
Log.v("Bill No", ""+bill_no_excist_or_not);
My DB Code,
String billno_exist_or_not(String bill_number){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_BILL_DETAILS, new String[] { KEY_BILL_NUMBER }, KEY_BILL_NUMBER + "=?"
+ new String[] { bill_number }, null, null, null, null);
//after this i don't know how to return the values
return bill_number;
}
I don't know how to check the values which is already available or not in DB. Can any one know please help me to solve this problem.
Here is the function that helps you to find whether the value is available in database or not.
Here please replace your query with my query..
public int isUserAvailable(int userId)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select user_id from user_table where user_id = ?", new String[] {String.valueOf(userId)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
Make your KEY_BILL_NUMBER column in your table UNIQUE and you can just insert using insertWithOnConflict with the flag SQLiteDatabase.CONFLICT_IGNORE

Sqlite open helper insert else update?

I want to insert data successfully
Here is my code:
public void insertData(String strTableName,
ArrayList<HashMap<String, String>> arrListproductdatabase) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for (int i = 0; i < arrListproductdatabase.size(); i++) {
// cv.put(columnName, arrListOfRecord.get(i).get("name"));
cv.put(columnproductname,
arrListproductdatabase.get(i).get("product"));
cv.put(columnproductprice,
arrListproductdatabase.get(i).get("price"));
cv.put(columnproductquantity,
arrListproductdatabase.get(i).get("quantity"));
cv.put(columnproductid,
arrListproductdatabase.get(i).get("productID"));
cv.put(columnresturantID,
arrListproductdatabase.get(i).get("resturantID"));
db.insert(strTableName, null, cv);
}
I want that when I have to press add button again, that time it should check if the product is already inserted, and in that condition it should update and all.
I don't want to create any duplicate value.
Any help would be appreciated!
you can check for the distinct values in the db. please follow the link to have more details
android check duplicate values before inserting data into database
Set 'Product' field as unique key. So when duplicate value arrives from standard insert, it will simply return -1 and the error message will be swallowed.
You can control the behavior by using insertWithOnConflict (String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm) where you also specify a conflict algorithm that can be of values:
CONFLICT_ABORT
CONFLICT_FAIL
CONFLICT_IGNORE
CONFLICT_REPLACE
CONFLICT_ROLLBACK
Check out the reference for descrption of the conflict resolution types.
There is also an updateWithOnConflict
You can do that like this :
public boolean checkProduct(String product){
// shold open database here
Cursor mCursor =
db.query(true, DATABASE_TABLE, null, "product='" + product+"'", null, null, null, null, null);
if(mCursor != null){
mCursor.close();
// shold close database here
return true;
}
// shold close database first here also
return false;
}
Hope this helped you.

How do I make an update query in SQLite with where clause? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
update sql database with ContentValues and the update-method
I am using this code, but I want update it according to my ID.
public void updateforgotpassword(String data) {
// TODO Auto-generated method stub
ContentValues forgotpass = new ContentValues();
forgotpass.put("password", data);
try {
db.update(TABLE_NAME, forgotpass, null, null);
}
catch (Exception e)
{
String error = e.getMessage().toString();
}
}
How can I do this?
Assuming the row's ID is stored in the variable id and assuming that the column name is _id (which is standard), you can update like this
final String[] whereArgs = { Long.toString(id) };
db.update(TABLE_NAME, forgotpass, "_id = ?", whereArgs);
You can always use rawquery method in which the plain SQL query can be fired.
Or, you can use the "update" method provided by SQlite and in which provide two array, one for "whereargs" and one is "wherevalue"
use
"update [your table] set [your column]=value" in rowQuery method...
or,
db.update(TABLE_NAME, forgotpass, "KEY_ID = ?", whereArgs);
You have the option of supplying a where clause.
db.update(TABLE_NAME, forgotpass, "ID = ?", new String[]{paramUserID});
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#update(java.lang.String, android.content.ContentValues, java.lang.String, java.lang.String[])
public boolean updateAccountData(AccountModel account) {
boolean updated = false;
openDataBase();
try {
final ContentValues values = new ContentValues();
values.put("AccountName", account.getAccountName());
values.put("Lessee", account.getLessee());
values.put("BookingRedeliveryNumber", account
.getBookingRedeliveryNumber());
values.put("SurveyorName", account.getSurveyorName());
values.put("ManufacturerName", account.getManufacturerName());
values.put("State", account.getState());
values.put("TurnInMonth", account.getTurnInMonth());
values.put("TurnInYear", account.getTurnInYear());
values.put("CscMonth", account.getCscMonth());
values.put("CscYear", account.getCscYear());
myDataBase.update(ACCOUNT_MST, values, "AccountID = "
+ account.getAccountID(), null);
updated = true;
}
return updated;
}

Categories

Resources