Android Search Match 2 columns SQL Statement - android

I am following the Android SearchableDictionary tutorial here and code here, I get everything to work, and understand the code. However, for the life of me I cannot make the search look in 2 columns of the searchable sqliteDB. See the comment below for what I want to accomplish
public Cursor getWordMatches(String query, String[] columns) {
//This (original code) searches your query in the KEY_WORD column, which is the SUGGEST_COLUMN_TEXT_1 column.
//String selection = KEY_WORD + " MATCH ?";
// This searches your query across ALL columns of the table, not what I want because I have added additional columns to the sqlitedb table
//String selection = FTS_VIRTUAL_TABLE + " MATCH ?";
// This is what I want, to search my query in both the keyword and keydefinition columns, which is the 1 and 2 suggest column text
String selection = KEY_WORD +"OR" + KEY_DEFINITION+ " MATCH ?";
String[] selectionArgs = new String[] {query+"*"};
return query(selection, selectionArgs, columns);
/* This builds a query that looks like:
* SELECT <columns> FROM <table> WHERE <KEY_WORD> MATCH 'query*'
* which is an FTS3 search for the query text (plus a wildcard) inside the word column.
Things I have tried (there are more, but they are tiny modifications of the following formats):
String selection = KEY_WORD +"OR" + KEY_DEFINITION+ " MATCH ?";
String selection = FTS_VIRTUAL_TABLE+ " MATCH 'suggest_text_1:? OR suggest_text_2:?'";
I have also read the relevant sections of this, it did not help me because it again gave example of searching in 1 column and searching in all columns using the hidden db named column. I need to search for more than 1 column in a single SQL statement.

Related

SQLite query where selection in the column?

How would I write a query that selects where the selection is IN the column? I've only seen it where the column is in the selection like this:
String[] names = { "name1", "name2" }; // do whatever is needed first
String query = "SELECT * FROM table"
+ " WHERE name IN (" + makePlaceholders(names.length) + ")";
Cursor cursor = mDb.rawQuery(query, names);
I basically want the opposite of this.
My app is a recipe finding app so there is one column that has a string of ingredients for every entry. I want to be able to select the recipe where the input selection (let's say "chicken rice") was in the string of ingredients ("chicken rice onions...").
Is it possible to do this?
this is what my query looks like now
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {COLUMN_ROWID,
COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED, COLUMN_SPECIAL, COLUMN_DESCRIPT, COLUMN_ALLINGRED, COLUMN_INSTRUCT, COLUMN_IMGPATH},
COLUMN_ALLINGRED + "like '%" + inputText + "%'",
null, null, null, null, null);
Is your second query not working? You're not doing a "selection in column", it's just a simple text search. But it has many issues (besides performance). What if your ingredients are in a different order? For ex. rice chicken. You probably want to store each ingredient on its own and tokenize inputText and search for all matches of either of the tokens, and prioritize both. Text search is not easy, you'd be much better off offloading this to a service and making calls from the client. You shouldn't have so much offline data anyway, presumably you'll want to update it frequently.

Delete multiple rows using IDs?

How can I delete multiple rows by a list of IDs in Android SQLite database?
I have defined a general delete method in this manner:
protected void deleteWhere(String whereClause, String[] whereArgs) {
try {
databaseHelper.getWritableDatabase().delete(
getTableName(), whereClause, whereArgs);
} finally {
databaseHelper.close();
}
}
And now I'm trying to call it with a list of IDs:
public void deleteAll(Iterable<T> entities) {
Iterable<Long> ids = Iterables.transform(entities, getId);
String whereClause = getIdColumn() + " IN (?)";
String[] whereArgs = { TextUtils.join(",", ids) };
deleteWhere(whereClause, whereArgs);
}
If the ID list contains for example the values [1, 2, 42], then I assume the resulting SQL should be:
DELETE FROM tableName WHERE _id IN (1,2,42);
But this doesn't seem to work correctly. If the list contains only 1 ID, then it is correctly deleted. However, if I provide multiple values, than zero rows are affected. What am I doing wrong?
When you give a single string as whereArgs, a single string ends up in the SQL command, as if you had written this:
... WHERE _id IN ('1,2,42')
This would compare each _id value against the value '1,2,42', which of course does not work.
If you use three parameter markers and give three strings in the whereArgs array, you would end up with three strings, like this:
... WHERE _id in ('1','2','42')
This works only when the _id column has integer affinity, which is true for a column declared as INTEGER PRIMARY KEY, but not in the general case.
The Android database API does not allow query parameters to have any type but string.
When using integers, you should just insert them directly (as in ianhanniballake's answer):
String whereClause = getIdColumn() + " IN (" + TextUtils.join(",", ids) + ")";
You can't use whereArgs for IN statements due to the escaping done by whereArgs (unless you make a separate ? for each value) - instead, you have to embed the ids in your where statement:
String whereClause = getIdColumn() + " IN (" + TextUtils.join(",", ids) + ")";
deleteWhere(whereClause, null);
Each "?" will only bind to a single value. So if your id list has three values, your whereClause would need to be "_id IN (?,?,?)"

Android SQLite wildcard to select character pattern

I am using an SQLite database in Android. I want to query the database using a query like
SELECT * FROM Persons WHERE City LIKE '%nes%'
which would return the city Sandnes based on the character pattern 'nes' matching, as in: http://www.w3schools.com/sql/sql_wildcards.asp.
However, when I try to put this into android's
query (SQLiteDatabase db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String sortOrder)
method, using
selection = KEY_CODE + " LIKE ?"; and selectionArgs = new String[] {"'%" + query + "%'"};,
I get no results returned.
Can I do this in the android query? If so, how should I write it? And if not, is there an alternative way?
Thanks in advance.
You're building a "likeable" parameter that looks like this:
'%do you like me%'
The apostrophes should not be there: they belong to literal syntax, not to a pattern itself:
%now you like me%
Use
selectionArgs = new String[] {"%" + query + "%"};

What is the correct syntax for SELECT statement and WHERE clause?

I am trying to explore android and I just started using SQLite database. I'm wondering on what is the right syntax for selecting a single row from a table, where the row I want to select is from the value entered from a user using editText. Thanks in advance.
I'm going to disagree with both of the answers above. What if the user enters this query:
Bobby Tables'; drop table yourTable;
See: http://xkcd.com/327/
I believe you should do this instead:
String query = "select * from TABLE_NAME WHERE column_name=?";
String[] selection = new String[1];
selection[0] = users_entered_value;
Cursor c = db.rawQuery(query, selection);
ETA: Actually, the more I think about it, the more I think you're going in the wrong direction. If your app depends on a database query returning exactly one unique match to an arbitrary string entered by the user, it's probably going to be broken a great deal of the time.
What you should probably do is something like this:
String query = "select * from TABLE_NAME WHERE column_name LIKE ?";
String[] selection = new String[1];
selection[0] = "%" + users_entered_value + "%";
Cursor c = db.rawQuery(query, selection);
and then iterate through the results and pick a "best" match according to your own criteria.
Also, you should create the table with case-insensitive matching for the column(s) you're going to be searching.
SQLiteDatabase db;
db.rawQuery("select * from yourTable where your_column_name = 'users_entered_value' limit 1", null);
SQLiteDatabase db;
// make connection to your database ;
Cursor c = null ;
String SQL = "select * from TABLE_NAME where column_name='VALUE'";
c = db.rawQuery(SQL);
c contains your result array of query you fired.
You can retrieve values using loop.

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

Categories

Resources