I am stuck with one scenario in which I need to do complex query to get cursor. Don't know It is possible or not. Scenario is :
There are three tables in database.
Table Columns
Table-1 _id, name, number, ....
Table-2 _id, table1_id, col1, col2, ....
Table-3 _id, table2_id, col1, col2, ....
In these tables, when any record is inserted in table 2, corresponding table1 id is inserted in that record. Same for table2 id is inserted with table 3 record.
I want cursor for CursorAdapter to display list view of Table-3 data.
Cursor cursor = getContentResolver().query(TABLE_3_NAME, null, null, null, null);
Now need to add selection and selection args of Table-1 in this query.
Is it possible in Android?
You can use raw query to fetch from various tables. One example would be as below.
Cursor mCursor = db.rawQuery("SELECT * FROM Table-1, Table-3 " +
"WHERE Table1.id = <Whatever selection args you want> " +
"GROUP BY Table1.id", null);
This is just an example. You will have to change it as per your requirement.
You can write a SQL selection query (i.e. normal way) and you can execute using rawQuery() method.
For example:
Cursor cursor = db.rawQuery(selectQuery, null);
Related
I just started learning of android and come to section of Database and I inserted same record in it but now I want to fetch data from database only by name and display it in textview.
Help me
Thank You in advance
Please follow developer document.
https://developer.android.com/training/basics/data-storage/databases.html
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
FeedEntry._ID,
FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_SUBTITLE
};
// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
You access data by using a query which returns a Cursor.
A Cursor is like a spreadsheet table that contains columns and rows.
You tell the query what columns you want and imply the rows that will be returned via an optional WHERE statement.
The simplest of queries is base upon the SQL SELECT * FROM <table>;. This will select all columns (i.e. * means all columns) from the table as specified by <table> ( where would be replaced by a valid table name).
If you want specific columns then ***`` should be replaced with a comma delimited list e.g.SELECT name, address FROM would return a **Cursor** containing all the rows from the table with only the **name** and **address** columns from the table specified by`.
If you want to filter the rows returned then you can add a WHERE clause. e.g. SELECT name,address FROM <table> WHERE name = 'Fred', would return a Cursor containing only the rows that have Fred as the name column with only the name and address columns.
You cannot just type the SQL statments you need to either use the SQLiteDatabase rawQuery or query methods if you need to return a cursor.
Using rawQuery
rawQuery takes two parameters, the first being the SQL as a string, the second optional arguments (not covered here, so null will be used).
To obtain a Cursor with columns name and address and with only rows that have Fred you could use, assuming the table is called mytable :-
`Cursor mycursor = db.rawQuery("SELECT name,address FROM mytable WHERE name = 'Fred'";);`
where db is an instance of an SQLiteDatabase object.
However, rawQuery is not recommended as it is open SQL injection. rather it is recommended only for situations where it has to be used.
Using query
query has a number of overload variations as can be found here SQLiteDatabase.
For this example query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) will be used.
String table, is the name of the table to be queried.
String[] columns, is an array of column names.
String selection is the where clause (null for no where clause).
String[] selectionArgs is an array of arguments that replace the ? placeholder.
The rest of the parameters will be null as these are features that are not being utilised.
As such the code could be :-
String tablename = "mytable";
String[] columns = {"name", "address"};
String whereclause = "name=?"; //note use of placeholder ?
String[] whereargs = {"Fred"};
Cursor mycursor = db.query(tablename,
columns,
whereclause,
whereargs,
null,null,null
);
where db is an instance of an SQLiteDatabase object.
Accessing the Cursor
mycursor contains the data or perhaps not if there isn't a column with the name Fred.
The number of rows in the cursor can be obtained by using:-
int rowsincursor = mycursor.getCount();
Note! A returned Cursor will not be null. (a very common mistake)
To access the data you have to move through the Cursor. Initially the Cursor is before the first row. If you only expect or want the only/first row then you can use the Cursor moveToFirst method.
See Cursor for more move... methods etc
Once the Cursor is appropriately positioned you can use Cursor get methods to get the data. e.g. getString(int columnindex) will return the data as a String. columnindex is a 0 based offset of the column to be accessed. Using the Cursor's getColumnIndex(String columnname) can be used to eliminate errors made by miscalculating offsets.
As such the following could be used to set a TextView (note intentionally over cautious)
if (mycursor.getCCount() > 0) {
if (mycursor.moveToFirst()) {
mytextview.setText(mycursor.getString(mycursor.getColumnIndex("name")));
}
}
mycursor.close() // You should always close a cursor when done with it.
I am trying to fetch the last row from my SQLite database. Until now i have tried max,sql_sequence but nothing seems to work. I have to fetch the row values and assign it to a class variable.
Any help is appreciated as I am new to SQLite and Android.
Thanks..
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
then use cursor to read values
or
do it like this
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
or
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);
This should do what you want:
SELECT *
FROM food_table
ORDER BY _id DESC
LIMIT 1
Try This It May Help You It Gives Last Record Of Your Table
Cursor mCursor = db.rawQuery("Select * from TableName", null);
mCursor.moveToLast();
Now Get The Data From The Cursor
There is usually a table called sqlite_sequence which stores the highest primary key of all the tables in the SQLite db. So use the following
String selectQuery = "SELECT * FROM sqlite_sequence WHERE name = table_name";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
You can use modified query to in last row....but you have to sort in a order using any column like in my case I have a serial_no column in my Employee table so my query is
SELECT * FROM Employee ORDER BY serial_no DESC LIMIT 1
limit 1 is in your case because you want only last record only
I want to retrieve all the records in ascending order with a WHERE clause. But where to include the WHERE condition in my query? It is working fine for ascending order.
Here is my code. First I am working on this query but here I am not able to implement the ORDER BY clause.
Cursor tripdaycursor = sdb.rawQuery(
"select TripDay_Id, Tripday_Date, Tripday_ParsingDate,
Trip_Complete, TripDay_Endkm, TripDay_Count, Tripday_EndPlace
FROM TripDay WHERE Trip_Id="+record, null);
So I tried the code below for ascending order:
String recordid=Integer.toString(record), Trip_Id="Trip_Id", TripDay_Id="TripDay_Id",
Tripday_Date="Tripday_Date", Tripday_ParsingDate="Tripday_ParsingDate",
Trip_Complete="Trip_Complete", TripDay_Endkm="TripDay_Endkm",
TripDay_Count="TripDay_Count", Tripday_EndPlace="Tripday_EndPlace",
TripDay = "TripDay";
Cursor tripdaycursor = sdb.query(TripDay, new String[] {
TripDay_Id, Tripday_Date, Tripday_ParsingDate, Trip_Complete, TripDay_Endkm,
TripDay_Count, Tripday_EndPlace}, null, null, null, null,
Tripday_ParsingDate + " ASC");
But I want both conditions on a single query, with the WHERE clause and in ascending order. How to do that?
You can put "order by Column_Name" in your query after the where clause. Something like this, with the column you want to order by in ascending order
Cursor tripdaycursor = sdb.rawQuery("select TripDay_Id,Tripday_Date,Tripday_ParsingDate,Trip_Complete,TripDay_Endkm,TripDay_Count,Tripday_EndPlace from TripDay where Trip_Id="+record + " order by " + columnName,null);
This question already has answers here:
How do I join two SQLite tables in my Android application?
(4 answers)
Closed 8 years ago.
I have 2 tables in my database, for example: Table1: id (PK), data1 and Table2: id (PK), id_table1 (FK), data2. How can I make a query like that:
SELECT * FROM Table1, Table2 WHERE Table1.id = Table2.id_table1
GROUP BY Table1.data1
I'm using SQLiteDatabase and its query() method.
Cursor mCursor = db.query(true, new String[] {"Table1","Table2"},
new String[] {"Table1.id","data1", "Table2.id", "id_table1", "data2"},
"Table1.id=Table2.id_table1", null, "Table1.data1", null,null,null);
But there's a problem with the second arg - it's only possible to use String, not String[] (like new String[] {"Table1","Table2}). What should I do to make a query from multiple tables in that way?
Try this:
Cursor mCursor = db.rawQuery("SELECT * FROM Table1, Table2 " +
"WHERE Table1.id = Table2.id_table1 " +
"GROUP BY Table1.data1", null);
So when you need to JOIN Tables, you have to use rawQuery instead of query.
So your statement
String SELECT_QUERY = SELECT * FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id GROUP BY t1.data1;
I recommend to you use JOIN because it more faster and safer then your approach. So then your rawQuery method can looks like this:
cursor = db.rawQuery(SELECT_QUERY, null);
Have look at
rawQuery in SQLiteDatabase
Regards
I have two tables in my database table1, table2. I have a join query like this:
select a.*,b.* from table1 a,table2 b where a.field1=b.field1;
Its working fine while i test it in sqlite manager(sqlite browser). when i try to make it through java like this:
database.execSQL("select a.*,b.* from table1 a,table2 b where a.field1=b.field1;");
its saying return type is not cursor. How can i get it to cursor with join. I have to get that data and show in a listview
use like this:
String qry = "select a.*,b.* from table1 a,table2 b where a.field1=b.field1";
Cursor cur = db.rawQuery(qry,null);
String query = "select a.*,b.* from table1 a,table2 b where a.field1=b.field1;";
Cursor c = database.rawQuery(query, null);
/* do whatever you want with 'c' */
Following is an Example of rawQuery, you can add your Query Respectively.
String getRT = "SELECT count(*) from "+ DATABASE_PROFILE+";";
Cursor mCur = sqlitedb.rawQuery(getRT, null);
return mCur;
SQLiteDatabase.rawQuery(query, selectionArgs)
Use rawQuery method to design any sort of complex query you might need. In the reference there are many useful methods you might need.