android sqlite help to fire my own query? - android

hello guys i have a simple intersect query works fine for sqlite3 console on windows
But how can i fire it and retrieve results in android sqlite database.
eg.
SELECT b_name FROM bus,route,station WHERE s_name='STAITON_NAME'
AND route.b_id=bus.b_id AND route.s_id=station.s_id INTERSECT
SELECT b_name FROM bus,route,station WHERE s_name='STATION_NAME' AND route.b_id=bus.b_id AND route.s_id=station.s_id;

To fire a query, use rawQuery.
To pass two different station names, use two different parameters:
c = db.rawQuery("SELECT ... WHERE s_name = ? AND ..."+
"... WHERE s_name = ? AND ...",
new String[] { station1, station2 });

Related

Android SQLite rawquery not working for a query that works in sqlite3 command line & dbeaver

I am writing an android app for a condo complex to aid locating utilities for residents. I have multiple tables and am having trouble retrieving data from 1 of them, but only for 1 query out of 3. Note that I am using SQLiteDatabase.rawquery. Also, the query works in sqlite3 command line and dbeaver. The first usage of the app should have the column 'yours' all 0's (boolean false) and let the user later set theirs to 1 (true). So, first call should return no rows. Later calls 1 row.
Table definition is as follows:
CREATE TABLE units (
building int4 NOT NULL,
unit int4 NULL,
stack int4 NULL,
unit_id int4 NOT NULL,
stack_id int4 NOT NULL,
yours int4 NULL,
CONSTRAINT units_pk PRIMARY KEY (unit_id));
Query that fails in android but works in command line & dbeaver is as follows. I copied the non-args version straight into command line and it works aside from adding the semicolon. The args variation did not work either.
String query = "SELECT * FROM units WHERE yours = 1";
//String query = "SELECT * FROM units WHERE yours = ?";
//String[] args = new String[]{"1"};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(query, null);
//cursor = db.rawQuery(query, args);
The following 2 queries work, one with the asterisk (*) wildcard.
List<String> units = new ArrayList<>();
String query = "SELECT unit FROM units WHERE building = " + buildingSelected
+ " ORDER BY unit";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor;
try {
cursor = db.rawQuery(query, null);
cursor = db.rawQuery("SELECT * FROM units ORDER BY unit_id", null);
I am at a loss as to what is wrong and can't find an answer on the internet based upon my questions.
10/2/2019 Added the following to explain "not working".
From sqlite3 command line, ran the SQL statement to select all rows where yours = 1. No rows come back as expected since all rows have yours = 0 (false). Then update 1 row to set yours to 1. Ran same SQL statement and get 1 row as expected.
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> .tables
electric_meters gas_meters units water_valves
sqlite> SELECT * FROM units WHERE yours = 1;
sqlite>
sqlite> UPDATE units SET yours = 1 WHERE unit_id = 4561205;
sqlite> SELECT * FROM units WHERE yours = 1;
4561|205|5|4561205|45615|1
sqlite>
Run UPDATE again to put row back to yours = 0 to run app in studio. Updated code after rawQuery call to getCount() in variable rows.
cursor = db.rawQuery(query, null);
//cursor = db.rawQuery(query, args);
int rows = cursor.getCount();
And while I am gathering this information, I found a code error that was causing issues with the debug output. While the data looks valid with the right formats, I am not expecting rows to return but the 2 rows returned do have yours = 1. Note the code error was after the rawQuery call and during the extraction of the values in cursor into a Unit class instance.
This is probably bad form to change my question in the middle. The database I am looking at through sqlite3 command line is in the assets directory of the project. The app is using the one on the AVD under /data/user/0/.... They might be different. I have done a clean project a few times. I thought that would reset everything, including updating the database the app uses in the AVD. Can someone tell me how to make sure the database in the project gets repopulated into the AVD data structure?
I found a solution to my issue. Turns out the database in the AVD file structure was not getting updated when I thought it would: clean project, synchronise files, etc. The AVD database had values for yours = 1, so it was responding correctly. Ended up deleting the databases and then uploading from the assets project folder. Probably a better way, but I could not find it. Thanks.

How to fix empty string while fetching it from Database?

I am fetching a string from Database using the column id. When I enter a query in SQLite DB Browser it returns what is need but the same query returns nothing when coded through Java.
My Data Base contains a table named drugs which has 3 columns i.e. drug_id, drug_name and drug_overview. Using drug_id i am fetching drug_overview. I have tried the query in db browser which returns me the correct string from drug_overview but the same query returns nothing when coded through java.
SQLite DB Browser query:
SELECT * FROM drugs Where drug_id = 50;
JAVA CODE:
String query105 = "SELECT * FROM drugs Where drug_id = " + drug_id;
Log.e("TESTDB1","Drugs table query: " + query105);
Cursor c105 = db.rawQuery(query105,null);
if (c105 != null){
while (c105.moveToNext()){
String overview = c105.getString(c105.getColumnIndexOrThrow("drug_overview"));
Log.e("TESTDB1","Overview: " + overview);
}
c105.close();
}
Expected result is Overview: Acyclovir is an antiviral drug. It slows the growth and spread of the herpes virus in the body. It will not cure herpes, but it can lessen the symptoms of the infection.Acyclovir is used to treat infections caused by herpes viruses, such as genital herpes, cold sores, shingles, and chicken pox, as well as varicella (chickenpox), and cytomegalovirus.Acyclovir may also be used for purposes not listed in this medication guide.
But the actual result is Overview:
empty
. When i change the id in my query it gives the correct result from a different drug.
I am afraid that your problem may be with the actual data itself as Mike said in comment, I think your database in the files is old and you haven't copied the latest to folder. Try to re-install and delete old database
Your query returns 0 or 1 lines so I think you should use c105.moveToFirst() instead of c105.moveToNext(). moveToNext is supposed to be used for a list, not for a single entry. Do something like:
if (c105.moveToFirst()){
String overview = c105.getString(c105.getColumnIndex("drug_overview"));
// do something with the result
}
c105.close();

Sqlite select email column from content provider

I'm trying to select some data from sqlite, where the column represents an email address.
My query is like this:
Cursor countCursor = mContentResolver.query(
SubscribeContract.SubscribeEntry.CONTENT_URI,
new String[]{"count(*) AS count"},
"user = ? ",
new String[]{ userChatID },
null);
But it's returning nothing.
Querys on sqlite3 terminal is returning ok.
sqlite> select count(*) as count from subscribe where user = 'brunox17_7a84e0c5e635fb571b32f5be9d55dd0b734c2f57#boo-app.com';
count
21
I think the problem is because the column type is text, and I cant put quotes surrounding the selection arguments.
What API version are you testing on? The parametrized queries are supported from API11.
You can try the getCount() method on the Cursor object without specifying any where clause.

Android Sqlite subquery does not return any value

I am using the following query to get the list of item
Query="Select * from Item_List where idSubcategory = (Select _id from SubCategory_List where Name = ?)";
c = db.rawQuery(Query, new String[] { Search });
But it is returning no result.
I ran this query on the database which I pulled from the device as well as emulator. There I am getting proper result, But when I run it on device no data is returned.
Can you try a different way? Use execSQL() as explained in this link. It is exactly the same problem.
EDIT
Unfortunately i didn't notice that execSQL() return no data (the work day is ending, finally!). The only solution i have is to do a first query and the result of this one will be the parameter of second query.
EDIT 2
Try to add "IN" to your query, like this:
Query = "Select * from Item_List where idSubcategory in (Select _id from SubCategory_List where Name = ?)"

SQliteDatabase query construction problem in Android

I am trying to build a query in SQLite in Android. Query is very simple and looks like this:
SELECT
ifnull(object.icon_large, ifnull( object.image, item.IMG_DEF_COVER))
FROM
object , item
WHERE
object.id_item = 1 AND item.id_item = 1;
I've tried to use SQLiteDatabase.query(), but it can be used only for one table. Any suggestions how to combine queries or how to join them, using Android SQLiteDatabases query's syntax?
Thanks in advance!!!
#fox you can use rawquery() instead of query example:
SQLiteDatabase mydatabase;
mydatabase.rawquery("select * from a, b where a.id=b.someid", null);
or can use querybuilder's setTable() method to specify the joins example
builder.setTables(TABLEA+" LEFT JOIN "+TABLEB+" ON "+TABLEB+"."+KEY_ID+"="+TABLEA+"."+KEY_B_ID);
SELECT
ifnull(object.icon_large, ifnull(object.image, item.IMG_DEF_COVER))
FROM
object
JOIN
item
ON
object.id_item = item.id_item
WHERE
object.id_item = 1;
SELECT syntax

Categories

Resources