Android Database query - android

I have application, which downloads data from internet and is supposed to write it to DB using content provider.
private void addCurrency(Currency _currency){
ContentResolver cr=getContentResolver();
ContentValues values = new ContentValues();
values.put(CurrencyProvider.KEY_DATE, _currency.getDate().getTime());
values.put(CurrencyProvider.KEY_NAME, _currency.getName());
values.put(CurrencyProvider.KEY_NOMINAL, _currency.getNominal());
values.put(CurrencyProvider.KEY_VALUE, _currency.getValue());
String w=CurrencyProvider.KEY_NAME+" = "+_currency.getName();
if (cr.query(CurrencyProvider.CONTENT_URI, null, w,null , null).getCount()==0){
cr.insert(CurrencyProvider.CONTENT_URI, values);
}else
cr.update(CurrencyProvider.CONTENT_URI, values, w, null);
}
So, I'm trying either to update record if it exists, or to add new.
But I'm getting SQLite exception:
near "доллар": syntax error: , while compiling: SELECT * FROM currency WHERE (name = Австралийский доллар)

Try surrounding your name with quote
String w=CurrencyProvider.KEY_NAME+" = '"+_currency.getName() + "'";

Related

Android unable to escaping single quote character while SQLite database update

Hi in my database i have a string like "computer's" , i am fetching it from database and displaying listview, when i click on the list item it should store to one of my database table. I am doing it as below but it is getting crashed
public void updateFav(String key, int value) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
C_FAV=C_FAV.replaceAll("'","''");
values.put(C_FAV, value);
db.update(tableName, values, C_KEY + "='" + key.trim() + "'", null);
db.close();
}
Below is my trace
12-12 17:55:49.291: E/AndroidRuntime(18184): android.database.sqlite.SQLiteException: near "s":
syntax error (code 1): , while compiling: UPDATE fav SET favorite=? WHERE key='computer's'
You're escaping the apostrophes in C_FAV which seems to be a column name but not in key.
Consider using ? placeholder and bind arguments instead, e.g.
db.update(tableName, values, C_KEY + "=?", new String[] { key.trim() });

Android and SQLlite: escape quote and get it back

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);

Update singel cell of a row in an SQLite database on Android

I wont to update a single cell of a row in the database. However the row contains of 5 columns so and i would like to not passing all the other values as well as they should remain the same.
I have this code snippet:
Cursor cursor = db.query(STATION_TABLE, null, null, null, null, null, null);
//If the database already include some stations.
if(cursor.moveToFirst())
{
ContentValues stationValues = new ContentValues();
for(StopLocation station: stations)
{
stationValues.clear();
//The database already includes the station
if(cursor.getString(POS_STA_ID).equals(station.getId()))
{
values.put(KEY_STA_DISTANCE, "null");
db.update(STATION_TABLE, stationValues, KEY_STA_ID + "=?", new String[]{station.getId()});
}
The db.update method throws this exception:
java.lang.IllegalArgumentException: Empty values
Any ideas on how to solve this?
If I understand the question correctly and assuming you are always dealing with one row, there are two possible ways to approach this:
First:
Get the values of all fields in the entire row, and declare them as content values before updating:
ContentValues cv = new ContentValues();
cv.put("Field1","123");
cv.put("Field2","True")
Second:
Use execSQL() method:
String strSQL = "UPDATE your_table SET Field1 = foo WHERE POST_STA_ID = "+ station.getId();
myDataBase.execSQL(strSQL);

writing exception to parcel exception while updating contact name in android?

I need to update a column (cached_name) of table callog.calls in sql lite database in android.what I can't figure out is how to use update statement.I am unable to find anything regarding update command using cursor.kindly help.thanks in advance.
//number1 is the phone number against which I need to run update query in db.
//name is the string which I used to insert against number1..
String name=edittext.gettext().tostring();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(CallLog.Calls.CONTENT_URI,
null, null, null, null);
ContentValues value=new ContentValues();
value.put("CallLog.Calls.CACHED_NAME",name);
cur.moveToFirst();
while(!cur.isLast())
{
String number=cur.getString(cur.getColumnIndex(CallLog.Calls.NUMBER));
if((number.equals(number1)==true)
{
try{
cr.update(CallLog.Calls.CONTENT_URI,value,CallLog.Calls.CACHED_NAME+"=?",null);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getStackTrace());
}
}//if
cur.moveToNext();
}//while
Basically, the only line you actually need is the update :
String name = edittext.getText().toString();
ContentResolver cr = getContentResolver();
ContentValues value = new ContentValues();
// Note that there is no "" here. The value is a constant
value.put(CallLog.Calls.CACHED_NAME, name);
cr.update(CallLog.Calls.CONTENT_URI, values, CallLog.Calls.NUMBER+"=?",
new String[] { number1 });
This is equivalent to this raw SQL query:
UPDATE call_log SET cached_name = name WHERE number = number1;
There is no need for iterating over all the calls, that's what the where clause is for.
Also,
while(!cur.isLast())
prevents you from actually reading the last matching value. Don't do that. Use
while (cur.moveToNext())
when you need to iterate over a cursor (which you don't, here)
I strongly suggest you take a look at how cursors work, as well as how sql works.
(Also, out of curiosity, why do you need to modify the callLog table?)

Android - How to populate Content Provider only once on App install?

I have a database in my application that is used as a ContentProvider.
It holds settings values for the application, and when I install the application I
want it to add a hardcoded set of values just once.
This is how I am trying to do it at the minute.
if(settings.size()<= 0){
Settings s = new Settings("voipusernameTa", "xxxxxxxxx", "xxxxx",
"displayNameTa", "sip.networks.com", "sip.networks.com", "siprealmTa", 120);
addNewSettings(s);
}
And this is the addNewSettings method:
private void addNewSettings(Settings _settings) {
ContentResolver cr = getContentResolver();
String w = CiceroSettings._ID + " = " + _settings.get_Id();
Log.d("ADDNEW SETTINGS", "new setting id =" + _settings.get_Id());
Cursor c = cr.query(CiceroSettings.CONTENT_URI, null, w, null, null);
Log.d("CURSOR", "cursor created");
int dbCount = c.getCount();
c.close();
if (dbCount == 0){
ContentValues values = new ContentValues();
values.put(Settings._ID, _settings.get_Id());
values.put(Settings.VOIPUSERNAME, _settings.getVoipUserName());
values.put(Settings.VOIPAUTHID, _settings.getVoipAuthId());
values.put(Settings.PASSWORD, _settings.getPassword());
values.put(Settings.VOIPDISPLAYNAME, _settings.getVoipDisplayName());
values.put(Settings.SIPPROXYSERVER, _settings.getSipProxyServer());
values.put(Settings.SIPREGISTRAR, _settings.getSipRegistrar());
values.put(Settings.SIPREALM, _settings.getSipRealm());
values.put(Settings.EXPIRESTIME, Integer.toString(_settings.getExpiresTime()));
Log.d("CURSOR", "Values assigned");
cr.insert(CiceroSettings.CONTENT_URI, values);
Log.d("CURSOR", "Values inserted");
}
}
}
This works however each time the app starts it adds a new settings object and I only want it to app ONE object at the install of the application and thats it no more.
Has anyone a better solution for this? Or a reason why my code is flawed?
If you want to add default values to your SQL table, I think the best way would be to set them right after creating your table.
So if you are using SQLiteOpenHelper, in the onCreate method, you can call db.insert() right after creating your table so that those values will be created just once

Categories

Resources