Using CursorLoader to retrieve only UNIQUE values from SQLiteDatabase [duplicate] - java

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);

Related

Android SQLite take the first element from database column

I am working on a project and created a database with SQLite. In my database I have just two columns, column names are r_id and m_id. I want to take the first element of the r_id and assign it in to a string. The elements of the r_id column is like 1, 2, 3.. in this situation my String has to be 1.
My code; creating a db query:
There is no problem I can add data correcly.
my_table = "CREATE TABLE "my_table"("r_id" Text, "m_id" Text);";
db.execSQL(my_table );
Code to take the first element of the column;
public String getSetting() {
String result = "";
String[] columns = {"r_id"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(true, "r_id", columns, "row", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
databaseHelper.close();
return result;
}
The error I am getting:
android.database.sqlite.SQLiteException: no such column: row (code 1 SQLITE_ERROR): , while compiling: SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
The 4th argument of query() is the WHERE clause of the query (without the keyword WHERE) and for it you pass "row".
Also, the 2nd argument is the table's name for which you pass "r_id", but the error message does not contain ...FROM r_id... (although it should), so I guess that the code you posted is not your actual code.
So your query (translated in SQL) is:
SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
which is invalid.
But you don't need a WHERE clause if you want just the min value of the column r_id.
You can do it with a query like:
SELECT MIN(r_id) AS r_id FROM my_table
without DISTINCT and a WHERE clause.
Or:
SELECT r_id FROM my_table ORDER BY r_id LIMIT 1;
So your java code should be:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT MIN(r_id) AS r_id FROM my_table", null);
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
I used rawQuery() here instead of query().
Or:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(false, "my_table", new String[] {"r_id"}, null, null, null, null, "r_id", "1");
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}

Android Sqlite select Query if value is zero or 0

I am trying to program a get a query that will show data from COURSE table if the values are :
course_id=0
or
semester_id=0
or
level_id=0
or
level_code=Select level
or
grade=Grade
So any rows that have any of the values above should be showed :
public List<Courses> getListCourseError() {
Courses courses = null;
List<Courses> coursesList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
courses = new Courses(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3), cursor.getInt(4), cursor.getString(5), cursor.getInt(6), cursor.getString(7), cursor.getInt(8), cursor.getInt(9));
coursesList.add(courses);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return coursesList;
}
Thanks
I believe that you issue is that string values have to be enclosed in quotes. You are also not including course_id is 0.
So instead of "SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade"
use :-
"SELECT * FROM COURSES WHERE course_id=0 OR semester_id=0 OR level_id=0 OR level_code='Select level' OR grade='Grade'"
However the above is a candidate for SQL injection so really you should be utilising the selection args (2nd parameter), which will properly enclose strings on your behalf. So the more correct solution would be to utilise :-
String[] selectionargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE course_id=? semester_id=? OR level_id=? OR level_code=? OR grade=?", selectionargs);
However, it is recommended to only use the rawQuery method when need and that the conveniece query method be used. This would be :-
String whereclause = "course_id=? OR semester_id=? OR level_id=? OR level_code=? or grade=?";
String[] whereargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.query(
"COURSES",
null, //<<<< all columns (else String[] of columns)
whereclause, //<<<< WHERE clause without the WHERE keyword
whereargs, //<<<< arguments to replace ?'s
null, //<<<< GROUP BY clause
null, //<<<< HAVING clause
null //<<<< ORDER BY clause
);
Notes
- null results in the respective parameter to be ignored/defaulted (table name cannot be null). e.g. columns (2nd parameter) as null defaults to ALL columns i.e. *.
there are a number of different query method signatures. See SQLiteDatabase
The code above is in-principle code and has not been tested so there may be some errors.

Can't get any data from sqlite db on Android

I have a DB helper that does this function:
public Cursor getCourseNames() throws SQLException {
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",null, COURSE_ROWID, null, null, null, null, null);
}
The table it is pulling from looks like this:
private static final String COURSE_ID = "CourseID";
private static final String COURSE_NAME = "Name";
private static final String COURSE_CODE = "CourseCode";
private static final String COURSE_ROWID = "_id";
private static final String COURSE_CREATE =
"create table " +
"Course" + " ( " +
COURSE_ROWID + " integer primary key autoincrement, " +
COURSE_ID + "integer not null," +
COURSE_NAME + "text not null, " +
COURSE_CODE + "text not null" + ");";
In my main activity I try this and get a null pointer...
public void buildCoursetoChapterList(){
Cursor cursor = dbHelper.getCourseNames();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cursor, null, null);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
Anyone have an idea what my problem is?
I put data into the db earlier on:
if(dbHelper.checkCourseForData() !=null)
{
setContentView(R.layout.classlist);
}
else
{
dbHelper.addFirstClassToDb(course_code, name, course_id);
Log.d+i("Course added to DB", course_code + " " + name + " " + course_id);
}
tried this and still nothing, I want to select all the Name values within Course.
No clue... losing hope.
public Cursor checkCourseForData() throws SQLException {
String[] values = {COURSE_NAME};
Cursor mCursor = mDb.query("Course",values,COURSE_ROWID + "=" + "Name", null, null, null, null, null);
if (mCursor != null) { mCursor.moveToFirst(); }
return mCursor;
}
It should be this
public Cursor getCourseNames() throws SQLException {
String[] values = {COURSE_NAME};
mDb = mDbHelper.getReadableDatabase();
return mDb.query("Course",values,COURSE_ROWID, null, null, null, null, null);
}
Explanation :
the medthod in the api has been defined as
public Cursor query (String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
So you need to pass the strings accordingly.
User my example as a reference it works for me
private String name;
private String Events_Table = "events";
private String[] Columns = {"_id", "Name", "Date", "Time_Slot", "Venue", "Details", "EHName", "EHNumber"} ;
private String WhereClause = Columns[1]+"=?" ;
Cursor cursor = db.query(Events_Table, Columns, WhereClause, new String[] {name}, null, null, null);
Consider Reading this
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
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.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

need help with androids sql query

I have an error in that m
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
Cursor myCursor=db.query(true, DATABASE_TABLE, new String[]{KEY_ROWID,MONEY_FIGURE,SPENDING_DETAILS,DATE}
, KEY_ROWID , null, null, DATE+"="+currentDateTimeString, KEY_ROWID, null);
The query function by the androids api:
query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
What I am trying to do here is to say. give me all the data based on where the date equals
currentDateTimeString .
But I get an error on that statement..
dont ask me what the error is..when i remove the call to the method holding that query statement the error doesnt appear..so i guess it is an sqlexception
SOLVED MY ME:
Cursor myCursor=db.query(true, DATABASE_TABLE, new String[]{KEY_ROWID,MONEY_FIGURE,SPENDING_DETAILS,DATE}
,DATE+"='"+currentDateTimeString+"'" , null, null, null , KEY_ROWID, null);
I am trying to do this
SELECT MONEY_FIGURE,SPENDING_DETAILS,DATE
FROM SpendingManagmentTable
WHERE Date=# currentDateTimeString
If the column type is not number then have to use with ''
date='1/1/2011' not date=1/1/2011
Cursor c = db.query(DATABASE_TABLE, new String[] {{KEY_ROWID,MONEY_FIGURE,SPENDING_DETAILS,DATE},DATE+"='"+currentDateTimeString+"'", null, null, null, null);

Android - Fetching only rows with a value in a column in java

First of all, please bear with me, I have minimal experience with SQLite. I am writing an app in Java for the Android platform and I've run into an issue while attempted to query a SQLite database.
I have implemented a database and I am unsure of how to write a method which returns a cursor of only specific rows with a certain value in a certain column. Say there is a column titled "date", I would like to write a method which returns all the columns that do not have the value string "null" in the "date" column.
I know how to write a fetchAll() method and how to write a fetch() for specific rows given an ID, but I not multiple specific rows.
If anyone can help me it would be greatly appreciated.
These will return all the row where Date!=null
public Cursor fetch()
{
return db.query(DATABASE_TABLE,
null,
DATE + "!=''",
null,
null,
null,
null);
}
If you don't need all columns then use
public Cursor fetch()
{
return db.query(DATABASE_TABLE,new String[] {
DATE,
TIME
},
DATE + "!=''",
null,
null,
null,
null);
}
For fetching multiple row using curosor, Have a go with this, You could customize it for your need:
public List<String> getNotNullValues(String value) {
String[] resultCols = new String[] { "Give your result column name here" }; //u could specify multiple column name here
List<String> list = new ArrayList<String>();
int count = 0;
Cursor cr = getWord("DATE", "Your Table Name", "Value of the column",
resultCols,"!="); //Cr is the cursor for resulted query
if (null == cr) {
return null;
}
do {
list.add(cr.getString(0)); //Fill the list or whatever here while traversing with the cursor
} while (cr.moveToNext());
cr.close();
return list;
}
}
public Cursor getWord(String columnName, String tblName, String rowId,
String[] columns, String condition) {
String selection = columnName + condition ; //condtion for selecting a value : "= ?"
String[] selectionArgs = new String[] { rowId };
return query(selection, tblName, selectionArgs, columns);
}
here are the steps:
Form the query with condition, column name and required column name
Get the cursor to the resulting query
Move the cursor to the next record till cr.moveToNext() returns false
For further reference:
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!

Categories