How to remove unwanted characters from SQLite insert in android studio - android

When I was passing data from my server via JSON. I have got this error.
android.database.sqlite.SQLiteException: near "rusitha": syntax error (code 1): , while compiling: INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES ('583', 's.p.m.j.ilangasinghe.', '805250666v','18','0716090398','no.79,'rusitha',nuwarapara,maradankadawala.');
This is the code that I used.
for(i = 0;i<customerId.length();i++){
sqlite.execSQL("INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES ('"+customerId.get(i).toString()+"', '"+customerName.get(i).toString()+"', '"+customerNIC.get(i).toString()+"','"+customerAreaId.get(i).toString()+"','"+customerTp.get(i).toString()+"','"+customerAddress.get(i).toString()+"');");
}

The issue is that 'no.79, doesn't have a closing single quote.This is because rushita is enclosed in single quotes and is preceeded by a comma. In short the address is not being escaped properly so the single quotes around rushita are confusing SQLite.
Your options are to either replace the single quotes in the address with 2 single quotes e.g.
customerAddress.get(i).toString().replace("'","''")
Or to let this be done on your behalf by using bindings by using the extended signature execSQL method. e.g
sqlite.execSQL("INSERT INTO customer (id, name,nic,areaId,tp,address) VALUES (?,?,?,?,?,?)"), newString[]{customerId.get(i).toString(),customerName.get(i).toString(),customerNIC.get(i).toString(),customerAreaId.get(i).toString(),customerTp.get(i).toString(),customerAddress.get(i).toString()});
binding would be recommended over the previous method.
An alternative would be to use the insert convenience method e.g
ContentValues cv = new ContentValues();
cv.put("id",customerId.get(i).toString());
cv.put("name",customerName.get(i).toString());
cv.put("nic",customerNIC.get(i).toString());
cv.put("areaId",customerAreaId.get(i).toString());
cv.put("tp",customerTp.get(i).toString());
cv.put("address",customerAddress.get(i).toString());
long insertedId = sqlite.insert("customer",null,cv);
This would be the most recommended way.
It builds the SQL on your behalf,
binds the values,
returns the rowid of the inserted row
and as it binds the values it, like the extended execSQL, protects against SQL injection.
Note the above code is in-principle code and has not been checked, tested or run, so there may be some small errors.

you can escape Character properly for the JSON data you got before using them:
// JSON Escape Utility
public static String crunchifyJSONEscapeUtil(String crunchifyJSON) {
final StringBuilder crunchifyNewJSON = new StringBuilder();
// StringCharacterIterator class iterates over the entire String
StringCharacterIterator iterator = new StringCharacterIterator(crunchifyJSON);
char myChar = iterator.current();
// DONE = \\uffff (not a character)
while (myChar != StringCharacterIterator.DONE) {
if (myChar == '\"') {
crunchifyNewJSON.append("\\\"");
} else if (myChar == '\t') {
crunchifyNewJSON.append("\\t");
} else if (myChar == '\f') {
crunchifyNewJSON.append("\\f");
} else if (myChar == '\n') {
crunchifyNewJSON.append("\\n");
} else if (myChar == '\r') {
crunchifyNewJSON.append("\\r");
} else if (myChar == '\\') {
crunchifyNewJSON.append("\\\\");
} else if (myChar == '/') {
crunchifyNewJSON.append("\\/");
} else if (myChar == '\b') {
crunchifyNewJSON.append("\\b");
} else {
// nothing matched - just as text as it is.
crunchifyNewJSON.append(myChar);
}
myChar = iterator.next();
}
return crunchifyNewJSON.toString();
}
code originally from this site

Related

How to compare a String with a database table name?

I have a database table in my android app. I want to compare database table name with a particular string.
Here is my code
if(branchName == TABLE_NAME)
{
}
else
{
Toast.makeText(this,"table not available",Toast.LENGTH_LONG).show();
}
Here branchName is the string.TABLE_NAME is a static string and it is the name of the table.
Whenever I run this code, control goes to else part and shows the toast message.
Why? How can I fix that?
for comparing two string you must use equal or equalsIgnoreCase ... ...
if (branchName.equalsIgnoreCase(TABLE_NAME) ){
// do sth
}
else{
Toast.makeText(this,"table not available",Toast.LENGTH_LONG).show();
}
try this way.

Realm on Android - How to select multiple objects by list of ids (#PrimaryKey)?

I'm building an Android app with the Realm database.
I have a RealmObject subclass called Article which has an id field (it's and int and also a #PrimaryKey). I would like to pass to a query a list of ints (a Set, int[], or whatever) of article id's and retrieve only those articles.
In SQL would be like this:
SELECT *
FROM `table`
where ID in (5263, 5625, 5628, 5621)
I've seen it's possible to do this in iOS in this StackOverflow question.
How can I do this in Android? Thanks!
Edit: Just to inform, I also asked this on the GitHub repo here.
Update:
Realm 1.2.0 has added RealmQuery.in() for a comparison against multiple values. The documentation details all the available overloads. This one is the method we can use if our ids are Integers:
public RealmQuery<E> in(String fieldName, Integer[] values)
Original answer:
The answer from #ChristianMelchior returns all articles if the list of ids is empty. I want it to return an empty RealmResults<Article>. That's what I've ended up doing:
Set<Integer> articleIds = this.getArticleIds();
RealmQuery<Article> query = realm.where(Article.class);
if (articleIds.size() == 0) {
// We want to return an empty list if the list of ids is empty.
// Just use alwaysFalse
query = query.alwaysFalse();
} else {
int i = 0;
for (int id : articleIds) {
// The or() operator requires left hand and right hand elements.
// If articleIds had only one element then it would crash with
// "Missing right-hand side of OR"
if (i++ > 0) {
query = query.or();
}
query = query.equalTo("id", id);
}
}
return query.findAll();
Now realm v 1.2.0 support RealmQuery.in() for a comparison against multiple values.
The Realm Java API's doesn't support this yet unfortunately. You can follow the feature request here https://github.com/realm/realm-java/issues/841
The current work-around would be to build up the query yourself in a for-loop:
RealmResults<Article> articles = realm.allObjects(Article.class);
RealmQuery q = articles.where();
for (int id : ids) {
q = q.equalTo("id", id);
}
RealmResults<Article> filteredArticles = q.findAll();
This is the way Realm does it since 1.2.0:
public RealmQuery<E> in(String fieldName, String[] values) {
if (values == null || values.length == 0) {
throw new IllegalArgumentException(EMPTY_VALUES);
}
beginGroup().equalTo(fieldName, values[0]);
for (int i = 1; i < values.length; i++) {
or().equalTo(fieldName, values[i]);
}
return endGroup();
}
Previously this is how I did it
I just came across this post and I thought I could throw in my 2 cents on this. As much as I appreciate Christian Melchior and his answers I think in this case his answer is not working (at least in the current version).
I prefer to do it like this - I personally think it's more readable than Albert Vila's answer:
List<String> listOfIds = [..];
RealmQuery<SomeClass> query = realm.where(SomeClass.class);
boolean first = true;
for (String id : listOfIds) {
if (!first) {
query.or();
} else {
first = false;
}
query.equalTo("id", id);
}
RealmResults<SomeClass> results = query.findAll();

Multiple Query Condition in Android using ORMLITE

i want to make a simple query, with multiple conditions
I use OrmLite to map entity object.
Now I want to search for an object into my table.
Supposing i have a Person entity that maps PERSON table, what I want to do is to initialize an object with some parameters and search it.
Suppose a function searchPerson(Person oPerson)
If i pass an object OPerson like this
Id = null
Name = John
Age = null
Sex = male
Is possible to write a query to reach that goal? Something like this pseudo-code
pers = (from p in db.Table<Person>()
where (if OPerson.Id !=null) p.Id==OPerson.Id}
AND {(if OPerson.Name !=null) p.Name.Contains(OPerson.Name)}
AND {(if condition) where-contion}
select p).ToList();
I know that i can do multiple query in this way
list=PersonDao.queryBuilder().where().eq("name",OPerson.name)
.and().eq("sex",OPerson.sex").query();
but I want also to check if the value exists
where (if OPerson.Id !=null) p.Id==OPerson.Id}
#ArghArgh is close but doesn't have the ANDs right. The problem is that the AND statements are conditional on whether there were any previous statements. I'd do something like:
QueryBuilder<Person, Integer> queryBuilder = dao.queryBuilder();
Where<Person, Integer> where = queryBuilder.where();
int condCount = 0;
if (oPerson.id != null) {
where.eq("id", oPerson.id);
condCount++;
}
if (oPerson.name != null) {
where.like("name", "%" + oPerson.name + "%");
condCount++;
}
...
// if we've added any conditions then and them all together
if (condCount > 0) {
where.and(condCount);
}
// do the query
List<Persion> personList = queryBuilder.query();
This makes use of the where.and(int) method which takes a number of clauses on the stack and puts them together with ANDs between.
I think that you must use the QueryBuilder.
Try something like this
QueryBuilder<Person, Integer> queryBuilder = PersonDao.queryBuilder();
// get the WHERE object to build our query
Where<Person, String> where = queryBuilder.where();
if(oPerson.Name!=null)
where.like("Name", "%"+oPerson.Name+"%");
// and
where.and();
if(Person.Sex!=null)
where.like("Sex", "%"+oPerson.sex+"%");
PreparedQuery<Person> preparedQuery = queryBuilder.prepare();
Than you can call it in this way
List<Person> list = PersontDao.query(preparedQuery);

Boolean Logical Syntax and MYSQL syntax Issue

Am not a learner to boolean expressions but this seems to be giving me a bit of an headache.
In my app when i search for a user,I am recieving certain values from my datase using this MYSQL statement.
SELECT `u3`.`username`,
CASE WHEN `u3`.`username` IS NULL THEN 'Not Existing'
ELSE 'Existing' END is_following
FROM `userinfo` `u3` WHERE `u3`.`username` LIKE '%".mysql_real_escape_string($data)."%' OR `u3`.`email` LIKE '%".mysql_real_escape_string($data)."%'
UNION
SELECT `u2`.`username`,
CASE WHEN `u2`.`username` IS NULL THEN 'Follow'
ELSE 'Following' END is_following
FROM
`userinfo` `u1` LEFT JOIN `followers` `f`
ON `u1`.`username` = `f`.`source_id`
LEFT JOIN `userinfo` `u2`
ON `f`.`destination_id` = `u2`.`username`
AND (`u2`.`username` LIKE '%".mysql_real_escape_string($data)."%' OR `u2`.`email` LIKE '%".mysql_real_escape_string($data)."%')
WHERE
`u1`.`username` = '$name'
Now the syntax above would return these set of values, a username and My own metadata. For example it would return
set of values 1: (davies and Existing)[if davies is in the userinfo table] AND (davies and Following)[if davies is following halex in the followers table]
OR
set of values 2: (null and Not Existing)[if davies is not in the userinfo table] AND (null and not followed)[davies does not exist]
OR
set of values 3: (davies and Existing)[if davies is in the userinfo table] AND (null and Not Following)[if davies is not following halex]
These are the set of values i recieve and i need an if statement to sieve through so i can display to my users this simple information
davies and Following OR davies and Follow[if davies is not following halex] OR User Does not Exist
Now am not sure if i should change the structure of my SOL statement or i could get a better way of handling this logic with if and else statements
This was the structure of my if else statement but it doesn't seem to work the way i want it to
if(username != null && metadata.contains("Existing"))//user exist
{
value = username;
//user exists but skip
}else
{
if(username != null)
{
map = new HashMap<String, String>();
map.put(TAG_USERNAME, value);
map.put(TAG_METADATA, metadata);
listvalue.add(map);
}else
{
//user does not exist
Log.i("search ", "user does not exist");
}
}
The codes above belongs to android.
Thanks any suggestion is appreciated. Thanks again in Advance.
What if you split your query into two parts? Querying for one set of information at a time will make things simpler and easier to debug.
I could imagine doing something that looks like this (in pseudo-code):
query = "SELECT username
FROM `userinfo` `u3`
WHERE `u3`.`username` LIKE '%".mysql_real_escape_string($data)."%'
OR `u3`.`email` LIKE '%".mysql_real_escape_string($data)."%'"
var result = db.execute(query);
// set to true if the above query returns at least one row
bool user_exists = (result.RowCount() > 0)
var username = (user_exists)? result.GetRow().GetField("username") : null;
if(user_exists)//user exist
{
value = username;
//user exists but skip
} // ....
(I've only replicated the functionality pertaining to your UNION's first SELECT statement; the logic associated with the second statement can be similarly rewritten.)

i want to compare names in two different tables and then equal get details

i have two different tables.I want to compare the names in two tables,if both the names are equal then i want to get the details.how can i do that? please help me.
Here is the code:
Cursor cr=mDbManager.fetchnewcustomerdata();
Cursor cr1 = mDbManager.fetchinvoicecustomerdata();
cr1.moveToFirst();
//String address;
while (!(cr1.isAfterLast())) {
String name = cr1.getString(cr1.getColumnIndex("icstname"));
if(name.equals(cr.getString(cr.getColumnIndex("cname"))))
{
Toast.makeText(this,"equal",1000).show();
}
String address = cr1.getString(cr1.getColumnIndex("caddress"));
map.put(name, address);
nameAList.add(cr1.getString(cr1.getColumnIndex("icstname")));
cr1.moveToNext();
}
mDbManager.close();
}
I think two ways it is possible
1) Either you need to establish relationship between those tables using the name column you are thinking of same between two tables.
2) Two separate queries to database, where condition for both queries will be the name
You can use CursorJoiner
http://developer.android.com/reference/android/database/CursorJoiner.html
Firstly, the names are ordered .
Then, sort it as the following sample:
while( !eofInTable1 && !eofInTable2) {
String name1 = getFieldFromTable1();
String name2 = getFiledFromTable2();
int tmpResult = name1.compareTo(name2);
if(tmpResult == 0) {
doYourAction();
table1.moveToNext();
table2.moveToNext();
}
else if( tmpResult == -1) {
table1.moveToNext();
}
else {
table2.moveToNext();
}
}

Categories

Resources