I have to save some data inside of SQLLite. This text data can contain a quote ('). Is there a way to escape this char on insert, and get it back when getting the data from the database?
In particular, the name is a references to a file. So the file can be named like "hel'lo.file". Before escaping it to the database, it should be "hel''lo.file". But when i get it back i need again "hel'lo.file" to be certain that the string inside the db matches the file name.
I'm using a content provider and a SQLiteOpenHelper.
Inside my content provider, for the insert i'm doing this:
_id = db.insert(TextEditorContract.NoteEntry.TABLE_NAME, null, values);
My insert inside my activity:
ContentValues values = new ContentValues();
...
values.put(NoteEntry.COLUMN_TITLE, getFileTitle());
Uri recordUri = contentResolver.insert(NoteEntry.CONTENT_URI, values);
Use SQLiteOpenHelper - then you can use prepared statements. See this question: Android SQLite Example
EDIT
String file = "/storage/emulated/0/Note/hello 'world.txt"
String sql = "SELECT _id FROM Recents WHERE percorso=? ORDER BY _id ASC";
String[] data = {file};
Cursor cursor = database.rawQuery(sql, data);
Related
I am having a table named keywords in database.I want to retrieve data of alarm and location columns from this table and unable to retrieve them except for contact number.For now I am showing their values in a Toast but every time I run any query to show my alarm or location in Toast its empty.But my contact_number is always shown.Don't understand the cause of this problem .I have also checked my tables view and it is showing the values of alarm ,location in them.
Create Table keywords( contact_number text primary key , alarm text , location text )
and my insert function is
public boolean insertkeys (String alarm ,String location ,String contact){
SQLiteDatabase db = this.getWritableDatabase();
//ContentValues is a name value pair, used to insert or update values into database tables.
// ContentValues object will be passed to SQLiteDataBase objects insert() and update() functions.
// ContentValues contentValues = new ContentValues();
ContentValues contentValues = new ContentValues();
contentValues.put("alarm",alarm);
contentValues.put("location",location);
contentValues.put("contact_number",contact);
long ins = db.insert("keywords",null,contentValues);
long upd = db.update("keywords",contentValues,"contact_number = ?",new String[]{contact});
// db.close();
if(ins == -1 && upd == -1)
return false;
else
return true;
}
I am inserting plus updating my data every single time my save button is clicked.Can anyone here tell how can I write a query to retrieve data of these fields and set it to Toast or Edit text. I am new to Database and stuck here for about a week. Thanks in advance for help :)
You extract data via a SELECT query which is returned as a Cursor when using the Android SDK.
The Cursor is similar to a table in that it has a number of rows, each with a set number of columns as determined by what you select.
To get all rows the SELECT query would be along the lines of :-
`SELECT * FROM keywords`
To do this using the Android SDK you could use the SQLiteDatabase query convenience method e.g. for the above you could use :-
Cursor cursor = db.query("keywords",null,null,null,null,null,null);
check the links above for the values/parameters that can be passed and how they correlate with the SELECT statement.
You then traverse the returned cursor extracting the data, typically using the Cursor's move??? methods. Noting that most will return false if the move could not be made and also noting that the original position in the Cursor is before the first row
As such you could have a method that returns a Cursor as per :-
public Cursor getAllKeys(){
SQLiteDatabase db = this.getWritableDatabase();
return db.query("keywords",null,null,null,null,null,null);
}
You could then process all the rows using :-
Cursor csr = yourDBHelper.getAllKeys();
while (csr.moveToNext()) {
String current_contact_number = csr.getString(csr.getColumnIndex("contact_number");
String current_alarm = csr.getString(csr.getColumnIndex("alarm");
String current_location = csr.getString(csr.getColumnIndex("location"));
...... your code to Toast or use the retrieved values
}
csr.close(); //<<<<<<<<<< you should always close a Cursor when finished with it.
Additional
In regard to the comment :-
Cursor query which you have suggested I tried to make changes in it
like putting column and where clause but after that it returns me
nothing when I execute it.Could you tell me that query too.
The following could be a method to retrieve just the alarm according to a contact number.
public String getAlarmByContactNumber(String contactNumber){
String rv = "";
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(
"keywords", //<<<<<<<<<<<< the FROM clause (less the FROM keyword) typically the name of the table from which the data is to be extracted (but can include JOINS for example, for more complex queries)
new String[]{"alarm"}, //<<<<<<<<<< A String[] of the column names to be extracted (null equates to * which means all columns) (note can be more complex and include functions/sub queries)
"contact_number=?", //<<<<<<<<<< WHERE clause (less the WHERE keyword) note **?** are place holders for parameters passed as 4th argument
new String[]{contactNumber},
null, //<<<<<<<<<< GROUP BY clause (less the GROUP BY keywords)
null, //<<<<<<<<<< HAVING clause (less the HAVING keyword)
null //<<<<<<<<<< ORDER BY clause (less the ORDER BY keywords)
);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex("alarm"));
}
csr.close();
return rv;
}
The above assumes that you would only have/want one alarm per contact number.
The above is in-principle code, it has not been run or tested and may therefore contain some minor errors.
I have created a database in Sqlite Android Application, there are two fields in the table i.e Name and Email. I want to update the contents of the table, the query that i am using is.
db.update(TABLENAME,cv,"id=?",new String[]{String.valueOf(7)});
As this will update the content that have the ID 7, but i want to update the table by matching the name entered.
Add another Parameter like
db.update(TABLENAME,cv,"id=? AND Name=? ",new String[]{String.valueOf(7),NameValue});
Try
String where="id=? and Name=?";
db.update(TABLENAME,cv,where,new String[]{String.valueOf(7),NameValue});
To match the name instead of the ID, just replace the column name in the whereClause:
db.update(TABLENAME, cv, "Name=?", new String[]{"PanKush"});
pass your string array in update method...
public int Upadte(String name_value,String email_value,String new_name) {
ContentValues value = new ContentValues();
value.put("name",new_name);
return _sqliteDB.update(TABLE_NAME ,value," NAME "+"=?"+" and "+" EMAIL "+"=?",new String[]{name_value,email_value});
}
I have database with three columns.
I would like to query the database, based on one column which can have multiple values.
For single parameter we can the normal query method where cardName is String[]
Cursor cursor = database.query(Database.TABLE_COUPON_CARD, allColumns,Database.COLUMN_CARD_NAME + " = ?", cardName, null, null,null);
but if there are more than one value, I get a Android SQLite cannot bind argument exception
For multiple values of the same column we can use IN statement but, here how do I write the QUERY or how should i form the rawQuery
String whereClause = Database.COLUMN_CARD_NAME+ " IN(?)";
Cursor cursor = database.query(Database.TABLE_COUPON_CARD, allColumns,whereClause,new String[][]{cardName}, null, null,null);
Android QUERY doesnot take array of array.
What should the correct query be?
TEMPORARY SOLUTION
Currently I have created a method which dynamically creates the clause.
private static StringBuilder buildInClause(String[] myStringArray){
StringBuilder fullString=new StringBuilder();
fullString.append("(");
for(int i=0;i<myStringArray.length;i++){
fullString.append(" '"+myStringArray[i]+"' ");
if(i!=myStringArray.length-1){
fullString.append(",");
}
}
fullString.append(")");
return fullString;
}
If anyone has any other solution please do share.
For two values: IN(?,?). For three values: IN(?,?,?). Get the idea? Each ? corresponds to a single literal in the selection args array.
i'm unable to delete row in a table using sqlite 3.In my code i would like to compare two
values an then delete the data in a table but it is not possible please help me.
while(authCur.moveToNext())
{
db.delete("auth_tab",authCur.getString(0)+"=?" , new String[] { user });
db.delete("auth_tab", null, null);
}
Deleting data
Once data is no longer needed it can be removed from the database with the delete() method. The delete() method expects 3 parameters, the database name, a WHERE clause, and an argument array for the WHERE clause. To delete all records from a table pass null for the WHERE clause and WHERE clause argument array.
db.delete("auth_tab", "authCur.getString(0)=?", new String[] {user);
Simply call the delete() method to remove records from the SQLite database. The delete method expects, the table name, and optionally a where clause and where clause argument replacement arrays as parameters. The where clause and argument replacement array work just as with update where ? is replaced by the values in the array.
or
public void deleteContact(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(auth_tab, KEY_USER + " = ?",
new String[] { user) });
db.close();
}
WATCH more, and you tube video, how to delete.
For example, if i use following code to query some data from database.
Uri uri = Uri.parse("content://com.android.contacts/contacts?address_book_index_extras=true");
String selection = "LEFT OUTER JOIN (select raw_contact_id, data1 from data where mimetype_id = 5) AS phone_data ON(_id = phone_data.raw_contact_id)";
Cursor c = getContentResolver().query(Contacts.CONTENT_URI, null, selection, null, null);
What i want to ask is after the query method, does database copy its result set to cursor or just make cursor something like a pointer and point to the first line of result set and query for more data when we call `moveToNext'
thanks
Yes. It is a readonly copy of the DB.
From Android Developers:
This interface provides random read-write access to the result set returned by a database query. Cursor implementations are not required to be synchronized so code using a Cursor from multiple threads should perform its own synchronization when using the Cursor.