Issue with my sqlite query in Android application - android

I've got a problem with my Android application. I'm trying to query database with multiple tables and display the result in the application. It's a dictionary. The problem is my query doesn't work. I have no clue what I'm doing wrong.
Here is a sample of my code that I use for it. If you need any more information, just let me know.
Thank You.
try {
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT index_nom_adresse" + word[0].toLowerCase().trim() + " FROM adresse_definition JOIN definition ON adresse_definition.definition = definition.data_id ", null);
//Cursor cursor = dictionary.getDictionaryDatabase().query("adresse_definition", null, "index_nom_adresse= '" + word[0].toLowerCase().trim() + "' or definition= '" + word[0].toUpperCase().trim() + "' ", null, null, null, null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
if (word[1] == null || word[1].equals("English")) {
translatedWord = cursor.getString(2);
} else {
translatedWord = cursor.getString(1);
}
} else {
translatedWord = "The word is not in database";
}
cursor.close();
} catch (SQLiteException sqle) {
translatedWord = "The word is not in database";
}
here is a logCat i get when trying to search for word
03-20 14:34:17.341: I/SqliteDatabaseCpp(516): sqlite returned: error code = 1, msg = no such column: index_nom_adressebonbon, db=/data/data/com.example.application/databases/dict.db

The query should be:
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT index_nom_adresse" + word[0].toLowerCase().trim() + " FROM adresse_definition JOIN definition ON adresse_definition.definition = definition.data_id ", null);
otherwise the coulmn is not defined correctly.

First of all, your hiding the real error by catching the Exception and then say "the word is not in the database'.
The problem your likely to have, which is just a guess because of the limited amount of information you are giving, is passing the word in the SELECT, instead of in the WHERE clause.
Likely your SQL query needs to be something like this:
SELECT index_nom_adresse
FROM adresse_definition
JOIN definition ON adresse_definition.definition = definition.data_id
WHERE index_nom_adresse = word[0].toLowerCase().trim() OR definition = word[0].toUpperCase().trim()
This translates to:
String sql = "SELECT index_nom_adresse ";
sql += "FROM adresse_definition JOIN definition ON adresse_definition.definition = definition.data_id ";
sql += "WHERE index_nom_adresse = " + word[0].toLowerCase().trim() " OR definition=" + word[0].toUpperCase().trim();
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery(sql, null);
or (a better solution) (No clue how you would do the join, is the JOIN needed?)
Cursor cursor = dictionary.getDictionaryDatabase().query(
"adresse_definition",
new String[] {"index_nom_adresse"},
"index_nom_adresse= ? OR definition=?'",
new String[] {word[0].toLowerCase().trim(), word[0].toUpperCase().trim()},
null,
null,
null);
Please read up on Android and SQL: http://www.vogella.com/articles/AndroidSQLite/article.html
I have no tools here to validate the code, please comment or edit if there are errors.

Related

Getting the result of cursor and turning it into a string for TextView

This is my query :
Cursor nextdate(String Date) {
SQLiteDatabase db = this.getReadableDatabase();
String[] params = new String[]{String.valueOf(Date)};
Cursor cur = db.rawQuery(" SELECT MIN (" + colDateDue + ") FROM " + PAYMENTS + " WHERE " + colDateDue + ">=?", params);
cur.moveToFirst();
return cur;
}
I want to display the result of that query in a TextView but I don't know how to, so naturally I look for an answer. I find a few answers around and come up with this :
DatabaseHelper db = new DatabaseHelper(this);
String str = "";
if (c!= null) {
if (c.moveToFirst()) {
str = c.getString(c.getColumnIndex(db.colDateDue);
}
}
TextView.setText(str);
But I get the error
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Which got me a bit confused since the usual fix for that error is using cur.moveToFirst(); which is used in both instances... what am I doing wrong exactly?
try like this:
keep the column index as 0 because that cursor will have only one column.
DatabaseHelper db = new DatabaseHelper(this);
String str = "";
if (c!= null) {
if (c.moveToFirst()) {
str = c.getString(0);
}
}
TextView.setText(str);
You are attempting to use the index of db.colDateDue. However, that does not correlate with your actual query. You can happily pull the first result with:
str = c.getString(0);

Cursor from db.rawQuery SELECT SUM returns null: how to catch?

I'm running the following query,
Cursor c = db.rawQuery("SELECT SUM(surveycount) FROM surveyDB WHERE species = " + "'" + szSpecies + "' AND location = " + "'" + szLocation + "'", null);
With the database column "surveycount" declared as an INT when the table is created. The below code works fine except when no records are returned that have the target string values for szSpecies and szLocation at which point szSum is shown as null.
if (c.moveToFirst()) {
szSum = c.getString(0);
c.close();}
else{
//do nothing
Toast.makeText(getActivity().getApplicationContext(),"It was NULL",Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity().getApplicationContext(),"Surveycount SUM = "+szSum+" .",Toast.LENGTH_LONG).show();
How can I catch this errant cursor output?
First check if the cursor is not null and then see if the cursor.getcount() is greater than 0, only then try to retrieve values from cursor.
Updated code as below:
Cursor c = db.rawQuery("SELECT SUM(surveycount) FROM surveyDB WHERE species = " + "'" + szSpecies + "' AND location = " + "'" + szLocation + "'", null);
szSum="";
if(c!=null && c.getCount()>0)
{
c.moveToFirst()
szSum = c.getString(0);
c.close();
} else{
//do nothing
Toast.makeText(getActivity().getApplicationContext(),"It was NULL",Toast.LENGTH_LONG).show();
}
if(!szSum.equals(""))
Toast.makeText(getActivity().getApplicationContext(),"Surveycount SUM = "+szSum+" .",Toast.LENGTH_LONG).show();
getCount (): Returns the numbers of rows in the cursor
Okay, changing out this,
szSum = c.getString(0);
for this
iSum=c.getInt(0);
appears to have solved the problem with zero being returned when querying location or species qualifier combinations that lack common counts.
Thanks for the help...

getting error "Can't read row# 0, col# 2 from CursorWindow. Make sure your Cursor is initialized correctly."

I'm developing Android app. I'm trying to display a user input, however when I try to do that I get the above error message. I have no idea what I'm doing wrong.
Here is a code I use. Thank You.
try {
Cursor cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT catgram FROM adresse_definition WHERE definition='"+word[0].toLowerCase().trim()+"'", null);
//Cursor cursor = dictionary.getDictionaryDatabase().rawQuery("SELECT index_nom_adresse" + word[0].toLowerCase().trim() + " FROM adresse_definition JOIN definition ON adresse_definition.definition = definition.data_id ", null);
//Cursor cursor = dictionary.getDictionaryDatabase().query("adresse_definition", null, "index_nom_adresse= '" + word[0].toLowerCase().trim() + "' or definition= '" + word[0].toUpperCase().trim() + "' ", null, null, null, null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
if (word[1] == null || word[1].equals("English")) {
translatedWord = cursor.getString(2);
} else {
translatedWord = cursor.getString(1);
}
} else {
translatedWord = "The word is not in database";
}
cursor.close();
} catch (SQLiteException sqle) {
translatedWord = "The word is not in database";
}
dictionary.close();
check if you are selecting all the columns in your rawquery that you're going to get from cursor. Right now you are selecting only one column in you query and getting two columns in cursor.getString. Simply change the query to:
Select * from table_name Where ...
The code is reading only one column in the Cursor and column indexes are zero based.
"SELECT catgram FROM adresse_definition WHERE definition=word[0].toLowerCase().trim()";

Android SQLite database column data(string) get with the help of column Id

Anyone help me for getting column data from id(INTEGER PRIMARY KEY).
My Code is Below :
String selectQUERY = " SELECT * FROM " + dbh.TABLE_CONTACTS.toString() +" WHERE "+ dbh.KEY_ID +"="+ "1";
Cursor cr = db.rawQuery(selectQUERY, null);
if (cr.moveToFirst()) {
do
{
newArr.add(cr.getString(1));
} while (cr.moveToNext());
}
for(int i=0;i<newArr.size();i++)
{
System.out.println("id pos :- "+newArr.get(i));
}
Note :- newArr is a String type ArrayList.
Thanks.
You haven't provided much detail but it looks like you can use: cr.getLong(0)
Cursor cr = db.rawQuery(selectQUERY, null);
while (cr.moveToNext()) {
// Do something with cr.getLong(0) here
newArr.add(cr.getString(1));
}

How can i write join query in android sqlite?

Hi, I am new to android. I want to write query for join in sqlite. My code is -
public Cursor SearchCategory(SQLiteDatabase db){
//return db.query("category_master", null, "status = 'Active'", null, null, null, null);
String Category_Sql = " select category_master.*,count(*) as cnt from product_master " +
" left join category_master on product_master.category_id = category_master.category_id " +
" where category_master.status = 'Active' group by category_master.category_id having cnt > 0 ";
return db.query(Category_Sql);
}
but it generate error. Where am I wrong?
It would have helped more if you could cite the error description.
Try running the query first in Portable SQLite explorer
you can use rawQuery
db.rawQuery("Select a.column1,b.column1 FROM table1 a JOIN table2 b ON a._id=b._id", null);
it should work

Categories

Resources