How to delete one row in Android? - android

I have a problem when to deleting a row in ListView on android, I am using SQLite.
This is my class to delete a file (only need remove item the in database).
public void deleteCallWhenUploadSuccess(String fileNameWhis)
{
db = callDatabaseHelper.getReadableDatabase();
String where = CallDatabaseHelper.FILE_NAME + "=" + fileNameWhis;
db.delete(CallDatabaseHelper.TABLE_NAME, where, null);
}
And in class, I call to using this.
dao.deleteCallWhenUploadSuccess(filename);
But it throws exception:
e: "sqlite.SQLiteException: near "2016": syntax error (code 1):, while compiling:
DELETE FROM recordStatus WHERE fileName=109092 2016-03-17 01.018.03.mp3"
Seem it missing " mark near WHERE "fileName
I tried to add:
String where = CallDatabaseHelper.FILE_NAME + "=" + "'"'" + fileNameWhis;
But the error still exists. How to pass this error? And use DELETE statement to delete a file with fileName, in this case, it has many spaces and special characters in fileName?

Couple of things:
I would do a console log that spits out the file name at the top of the function, so you know its coming in formatted correctly
As pointed out in the other answer you also need to get a writeable database.
Use Where and WhereArgs in your query:
db = callDatabaseHelper.getWriteableDatabase();
String where = CallDatabaseHelper.FILE_NAME + " = ?";
String [] whereArgs = new String[] {fileNameWhis}
db.delete(CallDatabaseHelper.TABLE_NAME, where, whereArgs);
This is a safer way of doing queries, and may solve your issue.

You can delete this in an easier way
db.delete(CallDatabaseHelper.TABLE_NAME, CallDatabaseHelper.FILE_NAME + "=?", new String[]{fileNameWhis});

Related

SQLite - Match results based on string value issue

I'm currently having an issue with my SQL Lite code with regards to counting matching results. In my application the user will have the ability to add a new folder and give it a name. Before the folder is added to the application my code will check to see if a folder with the same name already exists if so it will prompt the user.
When using my code below I receive an error informing me the column doesn't exist. If I remove everything past WHERE then it works perfectly and counts every record within the table.
I've reinstalled the application and changed the database version so that its completely clean, just to make sure. I'm certain its only something very minor I'm missing.
public int countMatchingFolders (String folderName){
String countQuery = "SELECT * FROM " + Primary_Table + " WHERE " + Col_FolderName + " = " + folderName;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
Error message I'm receiving
android.database.sqlite.SQLiteException: no such column: testFolder (code 1): , while compiling: SELECT * FROM Folder_Table WHERE Col_FolderName = testFolder
Any assistance to help with the issue would be greatly appreciated.
The error is because the string value doesn't have quotes around it, so it is treated as a table name instead of a string. You should use a bound query argument to fix this. Bound arguments also prevent SQL injection attacks:
String countQuery = "SELECT * FROM " + Primary_Table + " WHERE " + Col_FolderName + " = ?";
Cursor cursor = db.rawQuery(countQuery, new String[]{folderName});
Note that you can do "SELECT COUNT(*) as row_count" ... to let the database engine count the number of records more efficiently.

Delete the last row in a table SQLite android

I am developing an android app where I want to delete the last row in one of my database table. I have tried the code below, but its throwing a syntax error.
public void deletelatestprofilefromsystemsettings()
{
String maxid = System_id + "="+"SELECT MAX ("+System_id+") FROM" +TABLE_SYSTEM_SETTINGS;
getWritableDatabase().delete(TABLE_SYSTEM_SETTINGS, maxid ,null);
}
Please help! Thanks!
You are lacking a space after the FROM, and subqueries must be written in parentheses:
String maxid = System_id + "=" +
"(SELECT MAX("+System_id+") FROM " + TABLE_SYSTEM_SETTINGS + ")";
You are trying to execute a DELETE with a SELECT in the same query. AFAIK you shouldn't do it. You have to execute the SELECT query first, in order to retrieve the desired id, then execute the deletion. In other words, execute Cursor c = getWritableDatabase().query(), read the id from the cursor, then use it in getWritableDatabase().delete().
Also, add a space after ") FROM", so it becomes ") FROM " in order to avoid a syntax error.

Android crash when delete record

in a table SQLite. I have a list of strings that I see is in a listview by button I delete each record.
But if for example in the written record and the word "caffè" everything works fine, but if it is written the word " caffe' "the app crashes why?
thanks
String nome = tv.getText().toString();
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(NomeTable.TABLE_NAME, NomeTable.NOME_CAT + "='" + nome_cat + "'", null);
db.close();
finish();
This is because the ' is a special character in SQL.
So you end up with ='caffe'' which is invalid due to double ''.
You want to instead use the whereArgs param as well.
db.delete(NomeTable.TABLE_NAME, NomeTable.NOME_CAT + "= ?", new String[]{nome_cat});
That will escape your ' character for you and shouldn't mess you the SQL.
I would think nome_cat contains some symbols not alowed by the SQL syntax. You might want to use SQLiteQueryBuilder to build your query.

SQLite Database Problem while delete

Hi to All I am new to Android.
I am using SQLite DataBase in my Application
meanwhile I am Written Queries using +
Like delete from tablename where value = + value;
this is my query
String delete_query = "delete from " + tableName
+ " where title = '" + title + "'";
database.execSQL(delete_query);
I want to write this Query using placeholder ?.
so that i tried
database.delete(tableName, title + "?" , new String[] {title});
instead "?" i tried (?)/('?')/'?'
but it is giving me an error....
can any one tell me how to write appropriate query using ?.....
Thanks in Advance.
Mahaveer
Make sure you have put the equal sign:-
database.delete(tableName, title + "=?" , new String[] {title});
As far as possible, try to use the less raw queries you can. Two advantages:
Query parameters will be escaped by the system (protection against SQL injection)
The code will be more readable
See the delete function of SQLiteDatabase class
public int delete (String table, String whereClause, String[]
whereArgs)
Convenience method for deleting rows in the
database.
table the table to delete from
whereClause the optional WHERE clause
to apply when deleting. Passing null will delete all rows.
Returns the number of rows affected if a whereClause is passed in, 0
otherwise. To remove all rows and get a count pass "1" as the
whereClause.
In your case:
final String where = "title=?";
final String[] args = new String[] { title };
database.delete(tableName, where, args);

SQLITE Selection and order by causing errors

i'm trying to get a query that returns rows only with a specified name, and sort descending by week (integer).
Everytime I try and run it it gives me a FC and logcat says
ERROR/AndroidRuntime(728): android.database.sqlite.SQLiteException: no such column: New: , while compiling: SELECT Name, Week, Total FROM notes WHERE Name=New ORDER BY WeekDESC LIMIT 10
public Cursor graphQuery(String name){
return mDb.query(DATABASE_TABLE, new String[] {KEY_NAME,
KEY_WEEK, KEY_TOTAL}, KEY_NAME + "=" + name, null, null, null, KEY_WEEK + "DESC","10");
}
It says that there is no such column, which doesn't make sense because it should be looking at the names in the row and returning the ones that match. Also if I put KEY_NAME + "=" + name as null, it says that there is no such column WeekDESC which doesn't make sense either cause it is just supposed to be sorting by an integer.
I have gotten this code working before, but I misplaced it and can't seem to get it working again... This is getting frustrating, any help is very much appreciated!
If you search by string, you should use a question mark as a placeholder, i.e.
return mDb.query(DATABASE_TABLE, new String[] {KEY_NAME,
KEY_WEEK, KEY_TOTAL}, KEY_NAME + "=?", new String[] { name }, null, null, null, KEY_WEEK + "DESC","10");
Or else it will break if the name contains spaces or special characters.
(If you really don't want to you the question mark, you need to put the string in quotes or double-quotes, but using a question mark is far more elegant and safe.)
Also: There is no space between "DESC" and the key you're sorting by. Use " DESC".

Categories

Resources