search data in SQLite - android

Can someone help me and tell me what's wrong here?
String date = "Samstag, 30.7.2011";
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
String load = "SELECT db_scheine FROM ZahlenUndDatum where db_datum= "+date+"";
Cursor c = myDB.rawQuery(load, null);
String test = c.toString();
Log.d("output", test);
I would like to search for the date in the database and then return the value of the record from db_scheine.

try adding moveToFirst()
Cursor c = myDB.rawQuery(load, null);
c.moveToFirst();
String test = c.toString();
The rawQuery() method, will create a cursor, which is initially placed before the first row. So you can do something like this:
Cursor c = myDB.rawQuery(load, null);
while(c.moveToNext()) {
// do stuff
}
Without skipping the first row :)
UPDATE:
Your date is giving problems as well, im guessing the db_datum field is a string, enclose the string in quotes like so:
String load = "SELECT db_scheine FROM ZahlenUndDatum WHERE db_datum= '"+date+"'";

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...
}
}

sqlite LIKE function doesnt works with comma?

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

Error retrieving cursor value as string

I have an SQLite-Database with four columns
ID
Name
symptoms
Medicine
My Helper class code
public Cursor getMedicine(String symptom1)
{
SQLiteDatabase db=helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT medicine FROM diseases WHERE symptoms = ?;",new String[] {symptom1});
c.moveToFirst();
return c;
}
And here is code of my activity class :
String med = "";
Disp_med_DBHelper medicalHelp = new Disp_med_DBHelper(this);
medicalHelp.open();
medicalHelp.getMedicine(Value1);
med = medicalHelp.getMedicine(Value1).toString();
t1.setText(med);
medicalHelp.close();
Where t1 is my textbox, and Value1 is the string that we need to send to database helper to query the database.
When I check output on my textbox, I get the following output
android.database.sqlire.SQLiteCursor#4174986
What should I do to get it fixed?
Method toString() returns string representation of object Cursor. You have to use method getString(int column) from Cursor class.
Something like this:
med = medicalHelp.getMedicine(Value1).getString(0);
More info: https://developer.android.com/reference/android/database/Cursor.html
use this method instead:
public String getMedicine(String symptom1) {
SQLiteDatabase db = helper.getWritableDatabase();
Cursor c = db.rawQuery("SELECT medicine FROM diseases WHERE symptoms = ?;", new String[]{symptom1});
if (c.moveToFirst()) {
return c.getString(c.getColumnIndex("medicine"));
}
return null;
}
and then in your activity:
med = medicalHelp.getMedicine(Value1)
if(med!=null){
t1.setText(med);
}
Even when the cursor contains only a single value, it still behaves as a cursor that might have multiple columns and multiple rows. So you have to go to the first row (with moveToFirst(), which might fail), and read the value from the first column (with getString(0)).
However, for this simple situation, there is a helper function that allows you to avoid having to muck around with a cursor:
public Cursor getMedicine(String symptom1) {
SQLiteDatabase db = helper.getReadableDatabase();
return DatabaseUtils.stringForQuery(db,
"SELECT medicine FROM diseases WHERE symptoms = ?;",
new String[]{ symptom1 });
}

SQLite extracting day from date issue

I have a DATE field in my database with format 'YYYY-MM-DD'. Now I want to extract only 'day' from that day i.e. 'DD'. My table name is 'date' and the column name where date is stored is 'lastDonated'. How do i do it... please look these codes for more details.
public String day() {
String b = "";
SQLiteDatabase db = getWritableDatabase();
String query = "???(what to place in here?)";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
b = c.getString(c.getColumnIndex("lastDonated"));
c.moveToNext();
return b;
}
I only have one row in the database
Use this query
SELECT strftime('%d', YourDateColumn) AS SomeAlias FROM YourTable
And get the value like this
b = c.getString(c.getColumnIndex("SomeAlias"));
Reference: https://www.sqlite.org/lang_datefunc.html

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