sqlite LIKE function doesnt works with comma? - android

I am wondering, my codes run but it doesn't return results as what I want. For example the data on my
column1 is : hotdog,bacon,cheese
and I want to search bacon. like query cant find bacon. but if I searched cheese or hotdog like query can find it. I think if the word surrounds with a comma. What do I need to do?
public ArrayList<String> getrecom(int recom1) {
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = dbHelperFoods.getWritableDatabase();
String selectQuery = "SELECT * FROM "+ recom.TABLE+" WHERE " +KEY_recom+ " LIKE '%"+recom1+"%'";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
result.add(cursor.getString(cursor.getColumnIndex("name")));
while (cursor.moveToNext()) {
result.add(cursor.getString(cursor.getColumnIndex("name")));
}
}
cursor.close();
db.close();
return result;
}

Related

Sqlite how to improve performance?

I have to make more than 300 selects from my database.
Each of those queries has to be called inside of a for each loop, here's an example:
for(int id : myids){
Cursor cursor = MyDatabaseHelper.runMyQuery(id);
while(cursor.moveToNext()){
//my stuff...
}
}
MyDatabaseHelper is an instance of a database helper class, the function is like this
public Cursor runMyQuery(int id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor ret = db.rawQuery("select Name, Surname, Age from PTable where Id = " + id, null);
return ret;
}
I've been told that the constant "open and close" of the db because of multiple queries it the cause of my performance issues and I should, instead, make a single query (using union etc).
Changing my code to a single query would mean changing the entire database, and I was hoping not to do that.
Is there anything I can do to improve the performance and keep the multiple selects at the same time?
Thanks
I think what you are looking for is the in clause.
Convert your myids into a string. Something like
String inClause = "(1,2,3)"
and you can use it as
"select Name, Surname, Age from PTable where Id in " + inClause
You can read more of the in operator here
You can return a single Cursor containing all the rows.
First change your runMyQuery() method to this:
public Cursor runAll(String list){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "select Name, Surname, Age from PTable where " + list + " like '%,' || id || ',%'"
Cursor ret = db.rawQuery(sql, null);
return ret;
}
So you pass to the method runAll() a String which is the the comma separated list of all the ids that you have in myids and with th eoperator LIKE you compare it to each id of the table.
You create this list and get the results in a Cursor object like this:
StringBuilder sb = new StringBuilder(",");
for(int id : myids){
sb.append(String.valueOf(id)).append(",");
}
String list = sb.length() > 1 ? sb.toString() : "";
if (list.length() > 0) {
Cursor c = runAll(list);
while(c.moveToNext()){
//your stuff...
}
}

compare sqlite with string

I saved Data in my SQL databank.
Now I want to compare this saved data, with a string
Something like this:
String example = "house";
Now I want to check, if "house" is already in the databank, with a if clause
something like this
if ( example == [SQL Data] ) {
}
else {
}
Now, how can I accomplish this ?
Do something like
String sql = "SELECT * FROM your_table WHERE your_column = '" + example + "'";
Cursor data = database.rawQuery(sql, null);
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
stolen from here
Writing my reply to Sharath's comment as an answer, as the code will be messed up in a comment:
Not saying your reply is wrong, but it's really inefficient to select everything from the table and iterate over it outside the database and it shouldn't be suggested as an answer to the question, because it's a bad habbit to do like that in general.
The way I usually do it, if I want to see if some record is present in the database, I do like this. Not gonna argue about using do-while over a normal while-loop, because that's about different preferences ;)
String query = "SELECT * FROM table_name WHERE column_name=" + the_example_string_to_find;
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
// Do whatever you like with the result.
cursor.moveToNext();
}
}
// Getting Specific Record by name.
// in DB handler class make this function call it by sending search criteria.
Records getRecord(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_Auth_Name, KEY_B_PRICE}, KEY_ID + "=?",
new String[]{name}, null, null, null,null);
if (cursor.getCount() > 0)
cursor.moveToFirst();
Records Records = new Records(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return book
return Records;
}
you need to first fetch all the data from the database and next check the data with what you obtained from the database.
Have a look at the link sample database example
suppose you got a cursor object from the database
cursor = db.rawQuery("SELECT yourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
if(cursor.getString(0).equals(example))
//do something which you want and break
break;
} while (cursor.moveToNext());
}

How to set the arraylist item to be add in to reverse order?

In My Application, I am going to store name of all the available tables from my database with this code:
public ArrayList<Object> showAllTable()
{
ArrayList<Object> tableList = new ArrayList<Object>();
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table'";
Cursor cursor = db.rawQuery(SQL_GET_ALL_TABLES, null);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
if(cursor.getString(0).equals("android_metadata"))
{
//System.out.println("Get Metadata");
continue;
}
else
{
tableList.add(cursor.getString(0));
}
}
while (cursor.moveToNext());
}
cursor.close();
return tableList;
}
Yes i am able to store it. But while i am going to display it in to ListView, it will display in such way that last created shown at last. I want to display the list of the table as Last created, display first in to ListView.
Please help me, What should I have to do in my code to set such way of displaying tables?
There are several ways to do it. The easiest is probably to change your SQL call by adding ORDER BY. Here's something you can try out:
To order the items ascending:
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name ASC";
Or descending:
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name DESC";
Alternative solution
Another option would be to do it like you're doing it right now, and instead go through the Cursor from the last to the first item. Here's some pseudo code:
if (cursor.moveToLast()) {
while (cursor.moveToPrevious()) {
// Add the Cursor data to your ArrayList
}
}
before return the values just call the method
Collections.reverse(tableList);
see the full code
public ArrayList<Object> showAllTable()
{
ArrayList tableList = new ArrayList();
String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table'";
Cursor cursor = db.rawQuery(SQL_GET_ALL_TABLES, null);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
if(cursor.getString(0).equals("android_metadata"))
{
//System.out.println("Get Metadata");
continue;
}
else
{
tableList.add(cursor.getString(0));
}
}
while (cursor.moveToNext());
}
cursor.close();
Collections.reverse(tableList);
return tableList;
}

Android get list of tables

Does anyone know the SQL to get a list of table names via code in Android? I know .tables does it through command shell but this doesn't work through code. Is it anything to do with the meta-data, etc.?
Just had to do the same. This seems to work:
public ArrayList<Object> listTables()
{
ArrayList<Object> tableList = new ArrayList<Object>();
String SQL_GET_ALL_TABLES = "SELECT name FROM " +
"sqlite_master WHERE type='table' ORDER BY name";
Cursor cursor = db.rawQuery(SQL_GET_ALL_TABLES, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
tableList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
return tableList;
}
Got it:
SELECT * FROM sqlite_master WHERE type='table'

Android SQLite rawquery returns only first record

My SQLite query returning only one record, However, the table has multiple rows
cursor=mydb.rawQuery("Select category from items;", null);
I have even tried GROUP BY but still wont work.
I am new to SQLite, would appreciate any help. Thanks.
First of all your string query must not be terminated so instead of passing it as:
"Select category from items;"
you should try passing it as:
"Select category from items"
as mentioned on this page.
Also, are you looping over the cursor? Here is an example of how to get data out of a cursor with a while loop:
ArrayList<String> results = new ArrayList<String>()
while (cursor.moveNext()) {
results.add(cursor.getString(0)); // 0 is the first column
}
First, search:
Cursor cs = myDataBase.rawQuery("Your query", null);
if (cs.moveToFirst()) {
String a = cs.getString(cs.getColumnIndex("your_column_name"));
cs.close();
return a;
}
cs.close();
return "";
Get the information from cursor:
if (cs.moveToFirst()) {
ArrayList<String> results = new ArrayList<String>()
do {
results.add(cs.getString(cs.getColumnIndex("your_column_name")));
} while (cs.moveNext());
}
Without if, I took error in my project. But this worked for me. By the way, your query doesn't look good. If you give some information about your database, we can help much more.
Use this to select all items from the table:
Cursor cursor = db.rawQuery("SELECT * FROM Tablename ,
null);
this can help you
public ArrayList<mydata> getallContents() {
ArrayList<mydata> lst = new ArrayList<mydata>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + GAMETABLE, null);
if (c.moveToFirst()) {
do {
lst.add(new mydata(c.getString(1),
c.getString(3),c.getString(4),c.getString(5),c.getString(6)));
} while (c.moveToNext());
}
db.close();
return lst;
}
you don't need raw query method. i think that the android way is better in this case:
db.query(items, category, null, null, null, null, null);
than use the cursor how already is written in the other comment.

Categories

Resources