Strange Problem with Cursor - Android - android

This is a method In my DataBase Class:
public Cursor fetchFavTitles() {
return myDataBase.rawQuery("SELECT rowid as _id, title
FROM table1 JOIN table2 JOIN table3 JOIN table4 JOIN table5 JOIN table6
WHERE fav = TRUE", null);
}
My SQLite database has 6 tables:
table1 => rowid, title, content, fav
table2 => rowid, title, content, fav
table3 => rowid, title, content, fav
table4 => rowid, title, content, fav
table5 => rowid, title, content, fav
table6 => rowid, title, fav
In my activity, I wrote this:
Cursor cursor = myDbHelper.fetchFavTitles();
and the application forces the close!
Any idea where I'm mistaken ?
UPDATE
This is a snapshot of the LogCat, I couldn't understand it, I filtered the output with android.database:
What I am trying to do is getting the title (type: TEXT) that have a fav (type: BOOL) with value TRUE From all the tables and display them in one ListView (using SimpleCursorAdapter).

Without understanding exactly what you're going for, I'm guessing you need to change your query to:
SELECT rowid as _id, title
FROM table1
WHERE fav = TRUE
UNION ALL
SELECT rowid as _id, title
FROM table2
WHERE fav = TRUE
UNION ALL
SELECT rowid as _id, title
FROM table3
WHERE fav = TRUE
UNION ALL
SELECT rowid as _id, title
FROM table4
WHERE fav = TRUE
UNION ALL
SELECT rowid as _id, title
FROM table5
WHERE fav = TRUE
UNION ALL
SELECT rowid as _id, title
FROM table6
WHERE fav = TRUE
This will take all the results where 'fav = TRUE' from each of the tables and put them all into one result set. If you don't want duplicates, you can change 'UNION ALL' to 'UNION'. Right now your query is failing because 'SELECT rowid as _id, title' doesn't know which of your tables to pull the 'title' field from.

Related

Android SQLite queries marked as Error by Android Studio

In one of my Android apps I use some SQLite queries that are starting to give problems since I've updated to Android Studio 3.0.
Despite I can compile and run the app they are marked as error.
These are the queries.
db.execSQL("INSERT INTO table1 (…) ... substr(replace(table2.field2, ',', ''), table1.field1, 1) … FROM table1 … WHERE …");
gives error in 'replace':
')' or expression expected, got 'replace'
I think this would work because replace returns a String.
And:
db.execSQL("DELETE FROM table1 WHERE table1.rowid IN (…)");
gives error in 'rowid':
column name or table name expected, got 'rowid'
I think this would work too because SQLite adds an implicit rowid to each table.
And:
db.execSQL("ATTACH DATABASE ? as newDB", new String[] { getDatabasePath(DATABASE_NAME_NEW).getPath() });
gives error in '?':
expression expected, got '?'
I've changed this query to this:
db.execSQL("ATTACH DATABASE '"+getDatabasePath(DATABASE_NAME_NEW).getPath()+"' as newDB");
Also:
db.execSQL("UPDATE table1 SET field1=0 WHERE field2 IN
(SELECT field2 FROM table2 WHERE field3 LIKE '%blablabla%' OR field4 LIKE '%blebleble%' OR (field5 LIKE '%bliblibli%' AND field6 NOT LIKE '%blobloblo%')
COLLATE NOCASE)");
Which gives these errors:
In 'field6 NOT LIKE':
')' or '.' expected, got 'NOT'
In 'NOCASE)':
BETWEEN, IN or semicolon expected, got ')'
I don't know what is wrong with this one.
Are these queries correct? In iOS are identical and they are working well.
UPDATE:
These are the full queries (unfortunately due to my client's security policy I have to change the name of the tables and fields, but I hope is ok to detect the errors).
db.execSQL("INSERT INTO table1 (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11, field12, field13, field14) " +
"SELECT t6.field1, t7.field2, t3.field4, t3.field5, CASE WHEN t5.field1='1' THEN '11' " +
"WHEN t5.field1='2' THEN '22' WHEN t5.field1='3' THEN '33' WHEN t5.field1='4' THEN '44' " +
"ELSE t5.field1 END AS newfield1, t4.field1, CASE WHEN t2.field1 = '0' THEN t4.field2 " +
"ELSE substr(replace(t4.field3, ',', ''), t2.field1, 1) END AS newfield2, t2.field4, '0', -1, '0', '1', -1, t8.field1 " +
"FROM table2 AS t2, table3 AS t3, table4 AS t4, table5 AS t5, table6 AS t6, table7 AS t7, table8 AS t8 " +
"WHERE t2.field2=t3.field3 AND t2.field3=t4.field1 AND t2.field3=t5.field2 AND t3.field2=t7.field2 AND " +
"t3.field1=t6.field1 AND substr(t5.field1, 1, 1) IN ('1', '2', '3', '4') AND substr(t5.field1, 2, 1) IN ('1', '2', '3', '4') AND t2.field5=t8.field2");
db.execSQL("DELETE FROM table1 WHERE table1.rowid IN (SELECT table1.rowid FROM table1, table4 AS t4 WHERE table1.field6=t4.field1 AND (((t4.field2 NOT LIKE '%%' || substr(table1.field5, 1,1) || '%%') AND (t4.field3 NOT LIKE '%%' || substr(table1.field5, 1,1) || '%%')) OR ((t4.field2 NOT LIKE '%%' || substr(table1.field5, 2,1) || '%%') AND (t4.field3 NOT LIKE '%%' || substr(table1.field5, 2,1) || '%%'))))");
db.execSQL("ATTACH DATABASE ? as newDB", new String[] { getDatabasePath(DATABASE_NAME_NEW).getPath() });
Changed to:
db.execSQL("ATTACH DATABASE '"+getDatabasePath(DATABASE_NAME_NEW).getPath()+"' as newDB");
And the error is gone.
db.execSQL("UPDATE table1 SET field13=1 WHERE field2 IN (SELECT t7.field2 FROM table7 AS t7 WHERE t7.field1='Text1' OR t7.field1='Text2' OR t7.field1 LIKE '%TEXT3%' OR t7.field1 LIKE '%TEXT4%' OR t7.field1 LIKE '%TEXT5%' OR t7.field1 LIKE '%TEXT6%' OR (t7.field1 LIKE '%TEXT7%' AND t7.field1 NOT LIKE '%TEXT8%') COLLATE NOCASE)");
#Wonton Here is a suggestion use MVP design this is where you have a Database Model where you have a bunch of get and set for each item in the database table.
Next handle all your CRUD in an Activity called DBHelper then you can make calls to it from any other Activity with a lot less chance of errors. YES I use db.execSQL but once you have the string to update or insert in DBHelper life is good Here is an example of code from a DBHelper Activity HINT read about MVP
/* Update Record in Database*/
public void updateDBRow(String rowid,String website, String username, String password, String question,String answer, String notes){
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(Col_WS,website);
cv.put(Col_UN,username);
cv.put(Col_PW,password);
cv.put(Col_SQ,question);
cv.put(Col_SA,answer);
cv.put(Col_NOTES,notes);
/*NOTE WHERE THE quotation MARKS ARE */
db.update(TABLE_INFO,cv, Col_ID + " = ?",new String[] { rowid });
db.close();
}

SqlLiteDatabase.query order by date column not working

I'm developing an Android app based on SqlLiteDataBase.
When I query the db using the query method, I want to order by a date column in ascending order.
It seems the ORDERBY is not working.
Cursor cursor = db.query("myTable", // The table to query
dbTools.tableColumns, // The columns to return
whereClause, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
"dateText" + " ASC" // The sort order
);
The cursor mquery field during debug shows the following:
SQLiteQuery: SELECT dateText, <some other columns here> FROM myTable WHERE dateText >= '2015-10-01 00:00:00' AND dateText <= '2015-10-31 23:59:59' ORDER BY dateText DESC
(I removed irrelevant columns for your convenience)
After running the query, I want to check whether I have any entry, so I call:
if (!cursor.moveToFirst())
Then I do some logic and whenever I want to move to next row on cursor I run:
if (!cursor.moveToNext())
dateText column is defined as DATETIME:
String query = "CREATE TABLE myTable (id INTEGER PRIMARY KEY AUTOINCREMENT, dateText DATETIME, <other columns here>)";
Can you please advise why the sorting is not working? The rows are not sorted when iterating over the rows on the cursor.
Example:
if I have rows for 1st, 2nd and 10th of November 2015, the sorting by ASC will give this sorting: 10->1->2
Sorting by DESC gives: 2->10->1
here what i propose to you to try :
SQLiteQuery: SELECT dateText, FROM myTable WHERE dateText >= '2015-10-01 00:00:00' AND dateText <= '2015-10-31 23:59:59' ORDER BY date(dateText) DESC
and Be-careful for :
Dest ==> Descendant
ASC ==> Ascendant
Good luck !!
I want to order by a date column in ascending order
But your code show
ORDER BY dateText DESC
Change it ASC is default option, so you can remove it
ORDER BY dateText ASC

Android strange syntax error query sqlite

I'm doing a simple query that counts the records ... but I get syntax error here: COUNT (field1). Have you any idea why? thanks
String sql = "SELECT _id, field1, field2, field3 COUNT(field1)
FROM Appoggio GROUP BY field1 ORDER BY field1 ASC";
You are missing a comma after field3
Try using:
String sql = "SELECT _id, field1, field2, field3, COUNT(field1)
FROM Appoggio GROUP BY field1 ORDER BY field1 ASC";

group and sort sqlite records

I have a table with the following cols
_id INTEGER PRIMARY KEY,
body TEXT,
category TEXT,
is_readed INTEGER,
date INTEGER
i have the records look the example
i have the following query
SELECT
_id, body, category, is_readed
FROM
table
GROUP BY
category
ORDER BY
category, is_readed, date DESC
i want show only the first record for category (regardless of whether is_readed is 0 or 1) but i want show first (if exist) the record with is_readed == 1. but sometimes show first record with is_readed == 0 even if exist one with is_readed == 1
Note: I'm using ContentProvider not raw queries
Update
after try a while with this roughly work
SELECT
_id, body, category, MIN(is_readed) as is_readed
FROM
table
GROUP BY
category
ORDER BY
category, date DESC
i still are making tests but I'm still not convinced
Examples
SELECT * FROM table ORDER BY category, is_readed ASC, date DESC;
_id|category|body|is_readed|date
19|Hogar|message1|1|1371449889136
16|Hogar|message2|1|1371449806704
15|Hogar|message2|1|1371449803825
11|Hogar|message3|1|1371448915930
5|Hogar|message4|1|1371447395055
4|Hogar|message4|1|1371447391394
23|Linea blanca|message2|0|1371450430216
26|Linea blanca|message1|1|1371450719124
24|Linea blanca|message4|1|1371450431604
21|Linea blanca|message1|1|1371449893835
20|Linea blanca|message1|1|1371449891488
17|Linea blanca|message3|1|1371449810104
13|Linea blanca|message3|1|1371448994173
12|Linea blanca|message2|1|1371448917864
6|Linea blanca|message4|1|1371447397387
22|Vehiculos|message3|0|1371450428817
14|Vehiculos|message3|0|1371449801144
25|Vehiculos|message4|1|1371450717115
18|Vehiculos|message4|1|1371449887682
10|Vehiculos|message1|1|1371448422563
9|Vehiculos|message4|1|1371448419438
8|Vehiculos|message3|1|1371448416315
7|Vehiculos|message4|1|1371448395644
3|Vehiculos|message3|1|1371447388887
2|Vehiculos|message1|1|1371447386126
1|Vehiculos|message2|1|1371447383557
My Update
SELECT
_id, body, category, MIN(is_readed) as is_readed
FROM
table
GROUP BY
category
ORDER BY
category, date DESC
_id|category|body|is_readed|date
4|Hogar|message4|1|1371447391394
23|Linea blanca|message2|0|1371450430216
14|Vehiculos|message3|0|1371449801144
#Hoan Nguyen answer
4|Hogar|message4|1|1371447391394
6|Linea blanca|message4|1|1371447397387
1|Vehiculos|message2|1|1371447383557
Expected result
19|Hogar|message1|1|1371449889136
23|Linea blanca|message2|0|1371450430216
22|Vehiculos|message3|0|1371450428817
I had to implement raw queries in my ContentProvider and also a subquery, but I think that can be performed without the subquery
SELECT
_id, body, category, is_readed, date
FROM
(
SELECT
_id, body, category, is_readed, date
FROM
table
GROUP BY
is_readed, category
ORDER BY
category ASC, is_readed DESC, date DESC
)
GROUP BY
category
SELECT
_id, body, category, is_readed
FROM
table
GROUP BY
category
HAVING
max (is_readed)
ORDER BY
category, is_readed, date DESC

rawquery() issue

I am using rawquery() for perform inner join, but this is not giving me any error and does not working, if i use this query directly into sqlite browser than this is working but in application this query does not work, following is my code, sorry for bad English communication
public void deleteFifo() {
final String MY_QUERY1 = "Delete from Items where res_id in (select _id from Favourite where _id not in (select _id from Favourite order by date desc limit 50))";
final String MY_QUERY2 = "Delete from Favourite where _id not in (select _id from Favourite order by date desc limit 50)";
db.rawQuery(MY_QUERY1, null);
db.rawQuery(MY_QUERY2, null);
}
Try:
db.delete(TableName, whereCondition, null);
i.e. in your case
db.delete("Items", "res_id in (select _id from Favourite where
_id not in (select _id from Favourite order by date desc limit 50))", null);
and
db.delete("Favourite ","_id not in (select _id from Favourite
order by date desc limit 50)");
Hope it helps !!

Categories

Resources