my app should delete a specific row in the sql database by this method
public void delete(int id){
open();
sqLiteDatabase.delete("item","id = "+id,null);
close();
}
and it should also delete all rows if the user want that by this method
public void deleteAll(){
cursor=sqLiteDatabase.rawQuery("select * from item",null);
cursor.moveToFirst();
i=1;
while (!cursor.isAfterLast()) {
sqLiteDatabase.delete("item","id = "+i,null);
i++;
System.out.println(i);
cursor.moveToNext();
}
}
when the user use deleteAll() alone it is work but when he use it after using delete() it delete all rows before the deleted one using delete()
is the problem in deleteAll() method ? and how to fix it?
Your delete() function only deletes rows with the given id. If you want to delete all rows, then just do
sqLiteDatabase.delete("item", null ,null);
There is no reason to write your own loop especially since you never use the Cursor anyway.
Additionally, you should never use string concatenation for the "where" clause in a SQL statement. Instead use "id = ?" and provide a String[] with the values:
db.delete("image","id= ?", new String[] {id});
Here is an example of how to delete a particular column with an id:
SQLiteDatabase db= this.getWritableDatabase();
db.delete("image","id= ?", new String[] {id});
Toast.makeText(context,"Delete successfully",Toast.LENGTH_LONG).show();
Hope this will work for you
Related
In the table I have 4 fields (note1, note2, note3, Note4). I want to delete all the data in note1 and note2. I have to add arguments to the method db.delete, but I have trouble.
public void delete() {
SQLiteDatabase db= mHelper.getWritableDatabase();
db.delete(noteTable.TABLE_NAME, null, null);
}
Delete always deletes entire rows.
To clear values in specific columns, use an update query, for example
ContentValues cv = new ContentValues();
cv.putNull("note1");
cv.putNull("note2");
db.update(noteTable.TABLE_NAME, cv, null, null);
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.
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.
I tried the following SQLite query:
int idServizo = 150;
String whereClause = id_servizio+" = '"+idServizio+" ' ";
ContentValues cv = new ContentValues();
cv.put("sync", 1);
int r = dbManager.updateTable("myTable", cv, whereClause);
Where fields sync and id_servizio are both integer.
The method updateTable is:
public int updateTable(String table, ContentValues values, String whereClause){
int r = mDb.update(table, values, whereClause, null);
return r;
}
// mDb is SQLiteDatabase object
All this works good.
But if I try this with the rawQuery() method:
public Cursor RawQuery(String sqlQuery, String[] columns){
return mDb.rawQuery(sqlQuery, columns);
}
The table is not updated! even if no error occurs.
int idServizo = 150;
String updateQuery ="UPDATE myTable SET sync = 1 WHERE id_servizio = "+idServizio;
dbManager.RawQuery(updateQuery, null);
Why does this not work?
This is because when a rawQuery is executed cursor is returned. Without the call to cursor.moveToFirst() and cursor.close() the database won't get updated.
int idServizo = 150;
String updateQuery ="UPDATE myTable SET sync = 1 WHERE id_servizio = "+idServizio;
Cursor c= dbManager.rawQuery(updateQuery, null);
c.moveToFirst();
c.close();
I dont know the need to call moveToFirst() but this works fine and the database gets updated.
Problem solved.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Can't works because rawQuery runs the provided SQL and returns a Cursor over the result set.
If I want to return a table I have to use rawQuery, otherwise no!
Increase the value of a record in android/sqlite database
You should use db.execSQL() instead db.rawQuery().
Instead of doing this:
Cursor c= dbManager.RawQuery(updateQuery, null);
c.moveToFirst();
c.close();
You just need this:
dbManager.execSQL(updateQuery, null);
----------------------------------------------------------------------------
Posting answer because sometimes many people (like me) not reading comments.
Most popular answer is not correct but Yaqub Ahmad's comment is correct.
Answer from CommonsWare explained in this answer:
rawQuery() is for SQL statements that return a result set. Use
execSQL() for SQL statements, like INSERT, that do not return a result
set.
----------------------------------------------------------------------------
Documentation for execSQL:
public void execSQL (String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
Documentation for rawQuery:
public Cursor rawQuery (String sql,
String[] selectionArgs)
Runs the provided SQL and returns a Cursor over the result set.
Your update call formats the ID as string, while the rawQuery call formats is as number.
Assuming that the ID in the table indeed is a string, use:
String updateQuery = "UPDATE myTable SET sync = 1 WHERE id_servizio = '" + idServizio + "'";
I query the table by using this function below
public Cursor getTableInfo() throws SQLException
{
return db.query(TableName, null,
null,
null,
null,
null,
null);
}
I got the error "View Root.handleMessage(Message)line:1704". I could insert the data but can't query the data. I called this function below
Cursor c = db.getTableInfo();
int cRow = c.getCount();
if (cRow == 0)
{
Toast.makeText(NewContact.this,
"No Record",
Toast.LENGTH_LONG).show();
}
In SQLite, is there any case-sensitive in the name of database, table, column?
Please help me.
Your db request looks ok and it should return all records from your table.
So maybe there are just no records in the table?
Also it's unclear whether you have problem with db related stuff or with smth else, because the code provided looks ok.
I would rather evaluate the outcome of c.moveToFirst() instead of c.getCount(). The latter means the cursor iterates over the whole dataset which is a more costly operation.