How to delete row from sqlite at listview Android - android

I have a listview and i am getting the data from sqlite database. My problem is to delete a row which user selected it from listview. I can delete all table by
dbConn.delete("Restobj", null,null);
But i cant delete a single row which is selected from listview.
Please Help

You essentially need to get the row id from the selected ListView item. Using the row id you can easily delete that row:
String where = "_id = " + _id;
db.delete(TABLE_NAME, where, null);
After deleting the row item make sure you get the ListView adapter cursor and do a requery. If you don't you will not see the updated table, hence updated ListView.

Make use of those other two parameters to the delete method. Take a look at the API documentation for more information.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete%28java.lang.String,%20java.lang.String,%20java.lang.String[]%29
Pass in something other than null.
Also, try searching on stackoverflow and/or Google for this topic. The answers are plentiful.

You need to supply the appropriate values to the database object. I'm assuming that dbConn is an instance of a database object. If that is the case, you can pass in dbConn.delete() with 3 arguments. The first argument is the table name. The second is the whereClause. This is something similar to:
"id = " + objectDatabaseId
The final variable in this case you can leave blank. The end result is something like:
String whereClause = "id = " + objectDatabaseId;
dbConn.delete("Restobj", whereClause, null);
As a side note, it's better to use constants when referring to table names and table columns as apposed to "Restobj" you should have something like RestObject.TABLE_NAME where the constant is defined as a static final String inside of the RestObject.
-Randall

Related

SQLite in Android can't delete row with multiple where clauses

Ok, so I'm trying to make my database delete an entire row if two conditions are fulfilled. I've tried using the delete(String tableName, String whereClause, String[] whereArgs) method as provided from the SDK
However, a row is deleted only if I put in ONE where clause, such as this:
mDatabase.delete(ItemTable.NAME, ItemTable.cols.NAME + " = ?",
new String[] {latestItem.getName()});
Wherein attempting to put in multiple WHERE clauses breaks the whole thing
mDatabase.delete(ItemTable.NAME,
ItemTable.cols.NAME + " = ? AND " +
ItemTable.cols.PRICE + " = ?",
new String[] {latestItem.getName(),
String.valueOf(latestItem.getPrice())});
I am completely out of ideas on how to tackle this. Any and all help is appreciated.
Ok guys, I figured out what was wrong.
Turns out the condition for checking the item name was returning TRUE but the item price condition wasn't. Apparently there was a mismatch with the sqlite data affinity of the itemprice() data.
I fixed this by forcing all column data affinities to be TEXT and storing my item price as a String through String.valueOf(getItemprice()). Everything works this way.
Thanks though for all your help!

Remove a SQLite string value from my table

I have a column in my SQLite table named 'img_name'. An example of data in that column: '/storage/extSdCard/img1.jpg /storage/extSdCard/img2.jpg /storage/extSdCard/pic3.jpg'. Lets say I wanted to delete an image. I would delete the corresponding word(path). Only problem is, I do not know how to delete a specific word(path) from that column.
Any help will be appreciated.
The way to "delete a specific word" is to update the existing value.
So you will need an UPDATE statement which selects the appropriate rows, and changes the value of the column. The new value will have to be "computed" from the old value, as you would do in a programming language, using string functions.
UPDATE column1
SET column1 = trim(replace(column1||' ','/storage/extSdCard/img2.jpg ',''))
WHERE column2 = 'example'
Note that this is an example only. The correct string manipulation required may be different. Your question does not specify your exact requirements.
Please consult the SQLite documentation and internet articles for details of string functions in SQLite.
Note that this would not be necessary if you didn't store more than one value in a column in each row.
You should get id of your string that you need to remove, and then pass it in to this:
public void deleteById(int id)
{
SQLiteDatabase db=getWritableDatabase();
String[] position =new String[]{id+""};
db.delete("img_name", "id=?", position );
}
Note: "id=?". Replace "id" in this statement by your id column

Determine Position in Android SQLite Database

I want to be able to find the position of a string in a column. I have an app where the user adds to a list which forms a card and when they swipe the card, it deletes. I'm new to SQLite and I'm having a bad time trying to delete the items I want.
Here's what I have so far:
c2.moveToFirst();
String contentLabel = c2.getString(c2.getColumnIndex("Content"));
db.delete("Lists", "Content = '" + contentLabel + "'", null);
Now the problem with this is that when I swipe the card away, say, on the third card, the first card gets removed and the card that was swiped away moves to the top of the list.
The most accurate way to delete the correct item from the Sqlite database is by specifying the unique ID of the item to be deleted.
Did you create your database with an _id column? If not you may be able to use Sqlite's default ROWID column instead - never tried it, but I believe that android automatically maps this to _id anyway.
You must add the ID number to your loader's projection, so that you have this value in your cursor when you fill your card views with data.
Assuming that your list items - or cards - are using a custom layout, you should have an implementation of CursorAdapter which fills the cards with data by either recycling an existing view, or creating a new view for each list item that is displayed.
When you populate each list item with data, in the cursor adapter, you should also call listItemView.setTag(cursor.getString(cursor.getColumnIndex('_id'))); on the card view. This will store the the associated Sqlite row id number in the card view. Which I believe is a Long.
In your item dismissed handler, you can then call listItemViewToDismiss.getTag(); to learn the ID number that you want to delete from your database. Note that we've stored this as a String, but View.getTag() will return an Object, so this will need to be cast back to string, like so:
String storedRowId = (String) listItemViewToDismiss.getTag();
Once you have the database row ID easily reachable, the rest is simple:
db.delete(URI, "_id=?", new String[] { (String) cardViewToDismiss.getTag() });
This will delete only the rows which have the unique id specified in the list item's tag - if you're using SQLite's AUTOINCREMENT on your _id column - which I hope you are - then this should only ever delete one row, or zero rows if it has already been deleted by another process.
If your content provider can handle URIs to individual items, then I think you can also insert the full URI of the current item (with an appended ID) into the view's tag and then simply call
db.delete( (String) viewToDismiss.getTag() );
... and let the content provider delete the correct item.
Some references
Cursor Adapter's getView method:
[http://developer.android.com/reference/android/widget/Adapter.html] (See getView() on that page)
Setting tags:
http://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object)
disclaimer
It's been a while since I've done this, and I wrote that code from memory, so I hope someone will correct me if this is no longer the best practice for Android development, or if I've made a stupid error.
As your code is now, you always delete the first item. Move your cursor to the element you want to delete, with the method cursor.moveToPosition(int position).
Change your code to this:
// position = position of the "swiped card" (e.g. for the third card position is 3)
c2.moveToPosition(position - 1);
String contentLabel = c2.getString(c2.getColumnIndex("Content"));
db.delete("Lists", "Content = '" + contentLabel + "'", null);
moveToPosition(int position) returns false if it fails to move to the position (e.g. there is no such position), so you may want to add some code to check this:
if (!c2.moveToPosition(position - 1)) {
//failed to move!
}
String contentLabel = c2.getString(c2.getColumnIndex("Content"));
db.delete("Lists", "Content = '" + contentLabel + "'", null);
Maybe this might help?
String cardLabel;
card.setOnSwipeListener(new Card.OnSwipeListener() {
#Override
public void onSwipe(Card card) {
lable = "[code to get the swiped card's text]"
}
});
db.delete("Lists", "Content = '" + cardLabel + "'", null);
Basically just add some type of listener to get the text of the card as it is swiped and delete where the text equals that found by the listener. The issue with deleting by the text could be that the user might have two cards with the same text, maybe accidentally added it twice, but when they try to remove the duplicate, this would delete both.
Querying this way with the user defined text might also open you up to sql injection. I'm not sure how or if Android has any mechanisms to handle that, but it's worth thinking about. I agree with the others saying the proper way would be to search by ID. If you wanted to do an ID automatically, you could add something like this to the CREATE TABLE SQL statement in your DB helper.
Lists._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Hope this was useful.
I thing you should use ormLite or greenDao and focus on your app and not fighting with sql.

Imported sqlite database is missing data and mixing columns

I have put an sqlite database in my assets folder and imported it onto the phone.
I created an object with multiple properties and when I create a list of that object and assign each property a value from a column of the table they get mixed up
Below is my code
public ArrayList<Exercise> getExercisesFromQuery(String Query) {
ArrayList<Exercise> ExerciseList = new ArrayList<Exercise>();
Cursor cursor = mDb.rawQuery(Query, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Exercise e = new Exercise();
e.setID(Integer.parseInt(cursor.getString(0)));
e.setName(cursor.getString(1));
e.setMuscle(cursor.getString(2));
e.setDescription(cursor.getString(3));
e.setFilepath(cursor.getString(4));
e.setSets(cursor.getString(5));
e.setReps(cursor.getString(6));
e.setEquipment(cursor.getString(7));
e.setPrimaryMuscle(cursor.getString(8));
e.setSecondaryMuscle(cursor.getString(9));
e.setDifficulty(cursor.getString(10));
// Adding contact to list
ExerciseList.add(e);
} while (cursor.moveToNext());
}
return ExerciseList;
}
The current problem is when I do object.getName it gives me the muscle and if I do object.getmuscle it is blank and there is no value but if I do object.getDescription it works fine.
It is not a problem with the database it works fine in any sqlite manager.
Any ideas as to what is wrong?
The reason why the columns are not being returned in the order you expect is not clear. They should come back in the order specified in your query or in the order they are on the table if you are doing SELECT *. However it is not really necessary to address that specific puzzle.
A more defensive and maintainable coding approach is to request each column's index from the cursor by using the getColumnIndexOrThrow method instead of hardcoding them. For example:
int ID_INDEX = cursor.getColumnIndexOrThrow("_id");
int NAME_INDEX = cursor.getColumnIndexOrThrow("name");
If the column doesn't exist you'll get an exception. If it does, you now have its index within the cursor which you can use in the calls to cursor.getString:
e.setID(Integer.parseInt(cursor.getString(ID_INDEX)));
e.setName(cursor.getString(NAME_INDEX));
So you no longer need to worry about what order the columns come back in and you won't need to change any hardcoded index values if your query changes in the future.
Make sure that the columns in the database are in the correct order - column Name should be the second column, column Muscle should be the third column.

Android SQLite delete multiple rows

I want to delete all rows in a table with a specific ID (not primary key).
I have tested two different methods, but they only remove the first row it finds with the specific ID:
db.delete(CalendarTable.TABLE_NAME, "repeat_group="+repeatGroup, null);
and
db.delete(CalendarTable.TABLE_NAME, "repeat_group=?", new String[]{Integer.toString(repeatGroup)});
None of these methods works, how can I remove ALL rows in a table with this specific ID?
Thanks in advance!
UPDATE:
Lol, the method above did work! It was just me the stupid one that called the my own method delete() instead of deleteRepeatGroup(), guess I'm too tired!
Anyways, thank you guys for taking your time.
If everything else fails, you can try the following. Get all rows in the table with the ID you are trying to delete and save the rowID's in an array. Then iterate over the array and delete each row.
I hope this works as expected
you can use
String urQuery = "delete from tablename where Id in ("
+ Id + ")";
here Id may have all ids separated by comma ex. "id1,id2".

Categories

Resources