Single quote in database - Android Software Development

Can't get rid of this error:
android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling:
Select correct from answers where correct = 'Between the airplane's climb angle and the horizon.'
Obviously, it's finding the single quote in ( airplane's ) and considering that the end of the statement.
I've tried:
correct.replaceAll(" ' ", " ''' "); //replace 1 with 3
correct.replaceAll(" ' ", " '' "); // replace 1 with 2
correct.replaceAll(" ' ", " "); // replace 1 with space
(NOTE: the spaces are NOT in the code, I just did that to make it readable)
I have no idea what's going on, IMO, it should work. Maybe I need to try:
String single = "'"; // single '
String double = "''" // double ''
correct.replaceAll(single, double); // ????
Everything I"ve read about sqlite3 is to replace one with two....
TIA,
Roots

\'
\ is the escape character for most languages
so airplane's would be airplane\'s
Also, are you binding your queries with the "question mark" bind?

I'll try the escape and post back later. There are 1,000 rows in the database and I"m pulling a random subset of that, so it's not that often I get one of those situations.
I'm not sure what you mean by "binding with ?" Isn't that what you use for bind variable unknown at runtime? I know my bind variables and just use it in my dbquery. Please enlighten me...always happy to learn something new
Sample code...answerOne would contain the single quote that's killing me
Code:
Cursor c;
c = myDataBase.rawQuery("Select correct from answers where correct = '" + answerOne + "'", null);
if(c.moveToFirst())
answer = "1";
c.close();

binding with question marks should take care of escaping for you.
Basically the question mark is a place holder for a variable in the query.
What you are doing is manually creating the query string. This is considered bad practice these days especially with regards to security. Mostly because it opens up the DB to a SQL injection attack.
So instead of using the rawQuery just use query and you can put a ? in and android will substitute the value for you, all properly escaped:
Code:
String tableName = "answers";
String selectArgs = "correct=[COLOR="Red"]?[/COLOR]";
// if answerOne is string dont need String.valueOf
String[] selectVals = { String.valueOf ( answerOne ) };
String[] columnsProjection= new String[] {"correct" };
Cursor c = db.query(tableName, columnsProjection, selectArgs,selectVals,null);
So in that code the OS will replace the ? in selectArgs with the values in selectVals
This may seem like more writing at first but once you get in the habit it will be easy, reliable and more secure. It also allows you to bind multiple variables to mutiple question marks. It just binds then in the order it gets them.
so something like this:
Code:
String answerOne= "one";
String selectArgs = "correct=? AND age=? AND smiling=?";
String[] selectVals = { answerOne, "21", "yes" };

Ok, I'll try it. There are about 50 different queries in this program...for some reason I just decided to do a rawQuery on this one. I'll change it to "db.query(table name, new String[] {}....yada, yada).
Because, it just crashed and I decided to come back here and check for a solution.
Thank you very much!!!
Roots

Glad to be of help, just remember to hit the thanks booton ya Rooster

Still getting the error
Example: column is in table as text. Say it's equal to:
The driver's last name
Error comes back as "syntax error near 's' when compiling select correct from answers where correct = 'The driver's last name'
That single quote in driver's is killing my SQL.

Related

RIL_GetEquipmentInfo Problems

Trying to understand RIL and how to pass all the handles and various parameters. In my code i try to initialize RIL and then use the RIL_GetEquipmentInfo function to try and get some results from it. However when i try my application out , i get something like each time i press the command button ....
406
408
40B
411
....
it seems to increment and i thought i was ment to get something like HIMALAYAS back ... Where am i wrong ???
*********************************************
bool CTerminalDlg::RIL_Initialize(DWORD dwIndex)
{
TCHAR szString[256];
CEdit* pEditShow = (CEdit*)GetDlgItem(IDC_EDIT3);
result = ::RIL_Initialize(1, OnResultCallback, OnNotifyCallback, dwNotificationClasses, g_dwParam, &g_hRil);
HRESULT test = RIL_GetEquipmentInfo(g_hRil);
::wsprintf(szString, L" %X", test);
pEditShow->SetWindowText(szString);
return g_hRil != NULL;
}
the result is returned asyncronously via the OnResultCallback function.
alright i get ya ......... so that means the answer i should get ( HTC ) will be passed to a parameter inside the OnResultCallback function ? How would i display it in a message box though ?
thanks for your help i'm struggling here.
1)http://forum.xda-developers.com/viewtopic.php?t=28835
2)there is bad idea to show message box from callback
i think this callback execute in internal RIL thread
get data that you needed from RILEQUIPMENTINFO struct and put to temp buffer
show data from temp buffer in your main thread
for example:
in main thread
1)reset Event
2)call Ril_GetEquipmentInfo
3)wait Event
4)show MessgeBox
in callback
1)store data from RILEQUIPMENTINFO to temp buffer
2)set Event
3)return

[Q] Databases again

Currently i can create a database with following lines:
Code:
final String MY_DB_NAME = "Test";
final String MY_DB_TABLE = "Autos";
SQLiteDatabase myDB = null;
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + " (_id integer primary key autoincrement, name varchar(100), pos int(4))");
myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (name)" + " VALUES ('Audi TT')");
myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (name)" + " VALUES ('Honda Civic');");
Now this creates only name.
But i need to add a value too, what must i change to make it possible?
The table only has 3 fields..the autoincrement _id field which the database handles.
Then you have name and pos.
Not sure what you want to do, but to insert data to both columns, it's:
insert into autos ("name", "pos") values ("Chevy Camaro", 1);
If you need more information, you'll have to recreate (or alter) the table to add columns.
Currently i can create a database with the following lines:
Code:
private void onCreateDB () {
final String MY_DB_NAME = "settings";
SQLiteDatabase myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
Toast.makeText(set.this, "PATH: " + myDB.getPath(), Toast.LENGTH_SHORT).show();
myDB.execSQL("CREATE TABLE IF NOT EXISTS system (_id integer primary key autoincrement, name varchar(100), value int(4))");
myDB.execSQL("INSERT INTO system (name, value)" + " VALUES ('wifi_http_proxy', 'proxy')");
myDB.execSQL("INSERT INTO system (name, value)" + " VALUES ('wifi_http_port', '3128');");
myDB.close();
}
now, i must replace the entry by the name, not by the id. how can i do it?
ilendemli said:
Currently i can create a database with the following lines:
Code:
private void onCreateDB () {
final String MY_DB_NAME = "settings";
SQLiteDatabase myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
Toast.makeText(set.this, "PATH: " + myDB.getPath(), Toast.LENGTH_SHORT).show();
myDB.execSQL("CREATE TABLE IF NOT EXISTS system (_id integer primary key autoincrement, name varchar(100), value int(4))");
myDB.execSQL("INSERT INTO system (name, value)" + " VALUES ('wifi_http_proxy', 'proxy')");
myDB.execSQL("INSERT INTO system (name, value)" + " VALUES ('wifi_http_port', '3128');");
myDB.close();
}
now, i must replace the entry by the name, not by the id. how can i do it?
Click to expand...
Click to collapse
UPDATE system SET value = XX WHERE name = 'xxxx'
Do some googling for SQL. There is TONS of help for SQL out there, and it sounds like your problem isn't Android, it's SQL. There's some great learning resources out there.
i already got it, thx anyways.

[Q] Android basic authentication help

Hey all,
I've been trying to get my app to authenticate with a webserver. (Not my own webserver).
But I've been having major issues. I've looked all over for a proper way to authenticate and have tried different methods, but I keep getting the same errors.
I either get:
1. 401 authorization required
2. 400 bad request
3. Cookie gets rejected because of illegal path attribute.
4. 200 ok, but I'm not getting the proper site info that pertains to the authorized part of the site.
This all depends on the different methods I try.
Currently, this is the code I am using:
Code:
private int auth(String username, String password) throws IOException {
String login = username + ":" + password;
String auth = Base64.encodeToString(login.getBytes("US-ASCII"), Base64.DEFAULT);
int response = 0;
URL url = new URL(esims_login);
URLConnection conn = url.openConnection() ;
conn.setRequestProperty("Set-cookie", "OBBasicAuth=fromDialog");
conn.addRequestProperty("Authorization", "Basic " + auth);
conn.connect();
return response;
}
I end up getting a bad request response using this method.
The OBBasicAuth=fromDialog is a header from the server that is supposed to pop up a dialog that receives the username and password. So I added that to the initial request.
So my question is, what am I not doing/doing wrong?! I've been trying to accomplish this for weeks.
have you tried to trim the base64 encoded string ?
Code:
conn.addRequestProperty("Authorization", "Basic " + auth.trim());
Well, trimming the auth string helped, but now I am getting an expired session.

[Q] android open a password protected Website

I used this code:
Code:
mWebViewVertreungsplan = (WebView)findViewById(R.id.webViewVertretung);
mWebViewVertreungsplan.setVisibility(View.VISIBLE);
mWebViewVertreungsplan.setWebViewClient(new WebViewClient());
// Enable Javascript
WebSettings webSettings = mWebViewVertreungsplan.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebViewVertreungsplan.loadUrl("Username: Pasword @ domain. com");
On the on some devices it works, but on others it wont work. I geht the error 401 unauthorized.
Funny enough i am working on a project that has to do with a "substitution plan" as well (dunno what the correct english translation is) xD
You have to put the credentials inside the url header, and they have to be Base64 encoded
I use jsoup library to read the values from a pw protected site, so putting things into header is done differently, but same principle:
[...]Jsoup.connect("domain.com").header("Authorization", "Basic " + encodedString).post()
encodedString is done like that:
String text ="unamewd";
byte[] data = null;
data = text.getBytes("UTF-8");
encodedString = Base64.encode(data, Base64.DEFAULT);
So only thing you would have to google is how to set url header for webview

Help me translate this coding

I'm learning how to manage data that I pull from DB (MYSQL) from this coding. I tried to figure out from free source coding but got stuck on this function, can anybody explain to me flow of this coding?
Code:
protected void onPostExecute(Void aVoid) {
name = names.split(":");
email = emails.split(":");
phone = phones.split(":");
combinedArray = combinedText.split(":");
listView.setAdapter(new ArrayAdapter<String>(RetrieveData.this,
android.R.layout.simple_list_item_1, combinedArray));
progressDialog.dismiss();
}
and when I tried to use this code, red line prompt out and saying that cannot resolved this constructor on if i change
Code:
listItems
to
Code:
names
variables on this
Code:
adapter=new ArrayAdapter<String>(this,
R.layout.list_item, R.id.txtitem, listItems);
I don't understand why I need to use 'split' to pull out the output on listview.

Categories

Resources