Android delete row with cursor - android

I am creating a program in Android, on one of the screens I plan to iterate thought the rows in a database, presenting each row to the user and letting him skip it or delete it.
In Java I could user the ResultSet's deleteRow() method, however android currently has no equivalent method. Or event a method to set a column with a mark for deletion.
Would doing the deletion via the SQLiteDatabase delete or executeSql method would the currently opened cursor remain valid and would the deleted row be removed from it?
If it becomes invalid what advise is there to not have to keep re-querying the database (or at least not recompile the statement each time)?
If the cursor is still valid but not updated, would be the best way to ensure the user cannot return to this row?
Are there any better solutions to this problem?

Just build a list of item IDs to be deleted. Once the user operation is finished, you can delete the whole lot of them in a single step.

You can use MatrixCursor to do this:
newCursor = new MatrixCursor(new String[] {col1, col2, col3}); // col names
mCursor.moveToPosition(-1); // your Cursor
while (mCursor.moveToNext()) {
if (<any condition>) {
newCursor.addRow(indicationNames.rows(mCursor));
}
}
mCursor = newCursor ;
By this way you have your cursor updated without affecting the database.

Related

Moving android sql lite cursor forward

I have a Sql lite table in my application.
I want to add a cursor to parse the table such that it moves ahead from the current position.
Main idea is to update all next rows and not previous one.
can anyone give me a example cursor to do so with any loops if required ?
if (cursor.moveToFirst()) { //Replace this with cursor.moveToPosition(position) to iterate from that position to the end of your cursor, rather than from start to finish.
while (!cursor.isAfterLast()){
cursor.getInt(0); //get whatever information you require.
cursor.moveToNext();
}
if (!cursor.isClosed()) {
cursor.close();
}
}
There are many ways to achieve this. In the above example, I first check to ensure that the cursor isn't empty, and then go through each row one by one until I reach the final row. When done, I call close() on the cursor.

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.

SQLiteDatabase insert or replace if changed

I'm looking for a way to fill/update my SQLiteDatabase table.
On some occasions I need to be notified (by certain return value). Each row contains a url of a file that needs to be downloaded later.
row does not exist yet: insert it and notify me that this row should be listed for download.
row does exist but the one I'm trying to insert contains the same values as the one already in the db: do nothing, do not notify me that this should be downloaded.
row does exist and the one I'm trying to insert contains different values as the one already in the db: replace this row, notify me that this should be downloaded.
I've been looking for the answer but can't seem to find something good. Should I use insertWithOnConflict(), replace(), replaceOrThrow(), ...
Thanks!
Do it in two steps wrapped in a single sqlite transaction:
Query by rowid. If no rowid or or no result found, insert new and download.
Compare url of new row and row retrieved in step 1. Only if the urls are different, update the row and download, otherwise no-op.
First, you query if value exist in DB with cursor & if it's null you make an insert otherwise you make an update if the required field is different from what you have already.
In any other case do nothing
// Some pseudocode
Cursor cursor=_db.query("TABLE", null, TABLEID + "=?", new String[]{id}, null, null, null);
if(cursor.getCount()<1) // row Not Exist
{
cursor.close();
....assign values
SQLiteDatabase _db.insert("TABLE_Name", null, Table_object);
download ...ok
}
cursor.moveToFirst();
if( cursor[field] != "same_value" ) {
SQLiteDatabase _db.update("TABLE_Name", null, Table_object);
download ...ok
}

android sqlite delete row not working

I am having an odd problem deleting rows from a sqlite database. The first time I try deleting a row, it seems to work fine. However, anytime thereafter, I get no errors, it simply does not remove the selected row. If I uninstall the app and re-run it from eclipse (I have my tablet hooked up to my pc for testing) then the first delete works again.
Here is the code that I am using to populate a Gallery View from my database
Cursor cursor = _garmentAdapter.fetchAllLooks();
cursor.moveToLast();
final ArrayList<Bitmap> al = new ArrayList<Bitmap>();
_labels=new ArrayList<String>();
int totalGarments=0;
for(int i=cursor.getCount()-1; i>=0; i--) {
totalGarments++;
Bitmap bd=BitmapFactory.decodeFile(cursor.getString(3));
String label=cursor.getString(1);
al.add(bd);
_labels.add(label);
cursor.moveToPrevious();
}
Toast.makeText(BrowseLooks.this, "ITEMS=="+totalGarments, Toast.LENGTH_SHORT).show();
This toast message is displaying the number of items on screen. For example, if I create 3 items, then delete 1, it shows 2 on screen and the toast says ITEMS==2. However, if I delete another one, I still have 2 items on screen and ITEMS==2. So it seems the cursor is working correctly, but the database is not.
Here is the code for the delete row in the database:
return mDb.delete(LOOKS_TABLE, KEY_ROWID+"="+rowId, null)>0;
I have also logged rowId as being correct when mDb is called.
Once again, I am not getting any errors, the code is just not working. Any help would be very much appreciated.
Try this
db.delete(LOOKS_TABLE, KEY_ROWID+ " = ?",
new String[] { String.valueOf(rowId) });
I have found the answer to my problem. I did not fully understand the autoincrement of the sqlite database. Because of that, I was deleting rows that were already empty. The way the database increments is to create an entry higher than all previous entries not just the current highest entry. Therefore, the indexes of my on-screen items did not correspond to the indexes in my database table.

How to go through every record in SQLite db?

I think it's kinda easy one but still I'm new to android programming so please have patience. I want to know how can I get the number of records (rows) in a specific table in my db. I need this so I can create a loop to go through every record and add each one of it to the specific Array and display it later on. This is the source:
db.openDataBase(); // open connection with db
Cursor c = db.getTitle(5); // loop here through db, right now I'm fetching only one record
startManagingCursor(c);
//adding areas to the list here
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
db.close();
Does anyone can help me with this please? Thx in advance!
SELECT COUNT(*) FROM tablename
To get the number of rows in the cursor, use getCount.
To get the amount of total rows in a table, either use reinierposts solution, or do a select which select all rows in the table and get the count from the cursor. I'm guessing his solution is quicker though unless you actually need all the rows in the table.
Such a query would be:
SELECT * FROM footable;
You don't really need to get a count of how many first; instead, create a db.getTitles() function that returns all of the rows and returns a Cursor, then loop over the Cursor. Right now you probably have a query that looks something like SELECT ColumnA, ColumnB FROM Titles WHERE id = 5; just copy the function, remove the parameter and take off the WHERE clause so it looks like just SELECT ColumnA, ColumnB FROM Titles.
Then your code would look something like this:
db.openDataBase(); // open connection with db
Cursor c = db.getTitles();
startManagingCursor(c);
//adding areas to the list here
if (c != null && c.moveToFirst()) {
do {
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
} while (c.next());
}
db.close();
We check if the function returned a cursor at all, then move to the beginning of the cursor and start looping, going to the next item each time through. For more information on the Cursor interface see the API here, or to learn more about database access and related design practices better in general I suggest going through the Notepad tutorial.

Categories

Resources