adding DISTINCT keyword to query() with SQLite in Android - android

the difference between query() and rawQuery() in SQLite when making more complex SQL queries.
for example
i want to use the SQL keyword DISTINCT, so I don't get any duplicates returned from the database.
i understand how to use rawQuery() method, that way you can put an actual SQL query statement in the method. in this way i can make a standard SQL statement with rawQuery. it would be easy to add the DISTINCT keyword to any SQL statement when using rawQuery()
however, when using the query() method as shown here in this code, I can't just use regular SQL statements. in this case, how would i make a query with the DISTINCT keyword as part of the query? or something with the same functionality?
// get info from country table
public String[] getCountries(int numberOfRows) {
String[] columns = new String[]{COUNTRY_NAME};
String[] countries = new String[numberOfRows];
int counter = 0;
Cursor cursor = sqLiteDatabase.query(COUNTRY_TABLE, columns,
null, null, null, null, null);
if (cursor != null){
while(cursor.moveToNext()){
countries[counter++] = cursor.getString(cursor.getColumnIndex(COUNTRY_NAME));
}
}
return countries;
}

Instead of the...
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy)
...method you're using, just use the...
public Cursor query (boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit)
...overload and set distinct to true.
The Android docs seem a bit hard to direct link, but the doc page describing both is here.

you can use this,
Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN1 ,COLUMN2, COLUMN_NAME_3 }, null, null, COLUMN2, null, null, null);
Here first parameter is used to set the DISTINCT value i.e if set to true it will return distinct column value.
and sixth parameter denotes column name which you want to GROUP BY.

You should use another QUERY function with first DISTINCT boolean parameter set to TRUE
public Cursor query (boolean distinct, String table,...)

this is the function i used in my app for getting distict name from a group table hope you get an idea ,have a look at it.only distinct values will be fetched if the column contains same names
public ArrayList<String> getGroupNames() {
ArrayList<String> groups = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_GROUP_NAME};
//select distinct values for group name from group table
Cursor cursor = db.query(true,GROUPS_TABLE_NAME, projection, null, null, COLUMN_GROUP_NAME, null, null,null);
if (cursor.moveToFirst()) {
do {
String group=cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_GROUP_NAME));
groups.add(group);
Log.d("group",group+"gp");
}while (cursor.moveToNext());
}
return groups;
}

Related

execute multiple statement in single rawquery SQLite

can we execute multiple statement like SQL Server store procedure with Android SQLite rawquery
Example:
string statement1 ="create temp table .....";
string statement2 ="insert into temptable select ..... table1"
string statement3="insert into temptable select..... table2"
string statement4="select ...... from temptable";
Cursor cur=SQLiteDatabase db = this.getReadableDatabase().rawQuery(statement1+" "+statement2+" "+statement3+" "+statement4, null);
and is there alternate way to achive this?
db.beginTransaction();
try {
db.execSQL(statement1);
db.execSQL(statement2);
db.execSQL(statement3);
Cursor cursor = db.query(temptable, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
At the end use the cursor to get your results.

how to fetch data from sqlite by name

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.

Android sqlite distinct with multiple where parameters

I have a table "ActivityMeasurements", from which i would like to get all different "MeasurementAttemptId" values for all "Athlete" values passed in. The problem is that different Athletes can have same MeasurementAttemptId, and with following piece of code i'm getting many duplicates even if "distinct" query is set to true.
Here is my code:
List<String> measAttempts = new ArrayList<String>();
String[] wheres = new String[globalRunnersList.size()];
String questionMarks = "";
for(int i = 0; i < globalRunnersList.size(); i++)
{
wheres[i] = globalRunnersList.get(i).getAthleteId();
questionMarks += ",?";
}
questionMarks = questionMarks.substring(1);
Cursor mCursor = db.query(true, "ActivityMeasurements", new String[] {"ActivityMeasurement _id", "MeasurementAttemptId", "Athlete"},"Athlete IN ("+questionMarks+")", wheres, null, null, null, null);
if(mCursor.moveToFirst())
{
do
{
measAttempts.add(mCursor.getString(mCursor.getColumnIndex("MeasurementAttemptId")));
}
while(mCursor.moveToNext());
}
return measAttempts;
I know i could just add some code to do this after, but i think there should be another way to do this.
Any help appreciated,
Regards
Use
public Cursor query (boolean distinct, String table, String[] columns, selection, String[], selectionArgs, String groupBy, String having, String orderBy, String limit)
instead of
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
and set disctinct parameter to true.
Stupid me, i found a solution already.
The problem was that my query was for multiple columns:
{"ActivityMeasurement _id", "MeasurementAttemptId", "Athlete"}
this way every line was different from other, so i got many results.
Then i changed it to just this:
{"MeasurementAttemptId"}
and this returns wanted results.

How to get a cursor with distinct values only?

I want to return a cursor only with distinct values of a column.
The column 'Groups' has more items but with only 2 values: 1,2,1,1,1,2,2,2,1
String[] FROM = {Groups,_ID};
public Cursor getGroups(){
//......
return db.query(TABLE_NAME,FROM,null,null,null,null,null);
}
will return a cursor containing {1,2,1,1,1,2,2,2,1} but I would like to contain just {1,2}.
You can have an sql query like this,
public Cursor usingDistinct(String column_name) {
return db.rawQuery("select DISTINCT "+column_name+" from "+TBL_NAME, null);
}
you can use distinct argument while making query like this:
public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Follow this doc for more clearity.
You can use below example query, as you have to give column name for distinct
Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN_NAME_1 ,COLUMN_NAME_2, COLUMN_NAME_3 }, null, null, COLUMN_NAME_2, null, null, null);
COLUMN_NAME_2 - name of the column for distinct.
remember to add GROUP BY column names
Use boolean true iin the distinct argument, For example :
public Cursor query (**true**, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

Android sql query using WHERE clause

Dear Stack Overflow Community,
I have a question regarding how to incorporate a WHERE clause when querying a sql database in Android. My goal is to return specific records from my database where the date picked by a datepicker matches the date stored.
Here is my code:
private static String datePickerDate = "3/29/2011";
private static String[] FROM = { _ID, NAME, PRICE, DATE, TIME };
private static String ORDER_BY = TIME + " DESC ";
private static String WHERE = DATE + "is like " + datePickerDate;
private Cursor getEvents(){
// Perform a managed Query. The Activity will handle closing
// and re-querying the cursor when needed
SQLiteDatabase db = events.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
My questions are thus:
Where does my "WHERE" statement go?
And is my "WHERE" statement correct?
The documentation I found for db.query doesn't specify if a "WHERE" clause can be used, it just specifies that a "HAVING" clause is possible, but I don't quite think that's what I'm wanting.
db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
The selection represents your WHERE clause.
From the doc
selection A filter declaring which
rows to return, formatted as an SQL
WHERE clause (excluding the WHERE
itself). Passing null will return all
rows for the given table.
So you can try this (untested):
private static String WHERE = "DATE like ?";
db.query(table, columns, WHERE , new String[] { datePickerDate }, groupBy, having, orderBy)
If you want to use the WHERE clause, I would suggest using the raw query function in the SQLiteDatabase class, shown here.
This way, you can have the raw query typed out (or in segments) as if you were doing it naturally with SQL.
EDIT: On a side note, the "selection" parameter of the query() function corresponds to the WHERE clause, as noted here
About where you're "WHERE" goes - look here
And regarding the second part, I think you miss the qouts before and after the value, it should be .. like '3/29/2011' and not .. is like 3/29/2011

Categories

Resources