How do you iterate over a cursor in reverse order - android

Usually when I iterate over a cursor I use something like the following:
while (cursor.moveToNext()) {
// get stuff from the cursor
}
What's the best way to iterate an Android Cursor? has a nice discussion of the various options. But now I need to go backwards from last to first over the cursor.
So what can I do?

There are at least two options.
First, to specifically answer your question about iterating backwards over the cursor, you could do the following:
for (cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()) {
// get stuff from the cursor
}
Second, you could populate the cursor in reverse order from sql and then iterate over the cursor in your normal way:
SQLiteDatabase db = myHelper.getWritableDatabase();
String[] columns = { MyDatabaseHelper.TEST_DATE, MyDatabaseHelper.SCORE };
String orderBy = MyDatabaseHelper.TEST_DATE + " DESC"; // This line reverses the order
Cursor cursor = db.query(MyDatabaseHelper.TESTS_TABLE_NAME, columns,
null, null, null, null, orderBy, null);
while (cursor.moveToNext()) {
// get stuff from the cursor
}
cursor.close();
db.close();

You can start the cursor in the last position, and use moveToPrevious() until you've finished.
cursor.moveToLast();
do
{
// Stuff
}
while (cursor.moveToPrevious());

Related

CursorIndexOutOfBounds Exception: Index 0 requested, with a size of 0

I tried to read the SQLite database column and store each values in an String array. I did the following but it returned exception cursoroutofbounds. Help me figure out what I'm doing wrong?
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
String[] places = new String[c.getColumnCount()];
c.moveToNext();
for(int i=0; i<c.getColumnCount(); i++)
places[i] = c.getString(i);
return places;
}
Here :
String[] places = new String[c.getColumnCount()];
c.getColumnCount() will return count of column in row instead of number of rows in column. use c.getCount() to initialize places Array:
String[] places = new String[c.getCount()];
Or use ArrayList .
I worked out for sometime and found out the solution:
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
c.moveToFirst();
ArrayList<String> places = new ArrayList<String>();
while(!c.isAfterLast()) {
places.add(c.getString(c.getColumnIndex("place1")));
c.moveToNext();
}
c.close();
return places.toArray(new String[places.size()]);
}
You need to change your query and further processing at multiple places. Rectify your third parameter of query method to a proper where clause or keep it null. Loop through the cursor properly and add it to your String.
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
if (c.getCount() > 0) {
String[] places = new String[c.getCount()];
int i=0;
c.moveToFirst();
do {
places[i] = c.getString(c.getColumnIndex(0)));
} while (c.moveToNext());
return places;
}
c.close();
db.close();
}
First you have an issue with c = db.query("rates_table", columns, "place1", null, null, null, null);
The third parameter will result in no rows being selected.
You could use c = db.query("rates_table", columns, null, null, null, null, null); , which would return all rows.
Or you could use c = db.query("rates_table", columns, "place1 = 'myplace'", null, null, null, null);, in which case only rows that have the value myplace in the column place1 would be shown.
The best practice way is to use the 3rd and 4th parameter in conjunction where you use ? placeholders in the 3rd parm (e.g "place1=?") and corresponding args in the 4th parameter (e.g. new String[]{"myplace"}), so to replicate the previous query you could have c = db.query("rates_table", columns, "place1=?", new String[]{"myplace}, null, null, null);
Using c.moveToNext, will try to move to the next (initially the first) row of the cursor. However, if it cannot move (i.e. there are no rows, as would be the case as described above) it will not fail, rather it returns false (true if the cursor could be moved).
So You need to check this otherwise, in the case of no rows, an attempt to access a row will fail with Cursor out of bounds Index 0 requested, with a size of 0 (i.e. you requested the first (index 0) when the size of the cursors (number of rows) is 0.
There are various ways to check.
However I suspect you will then wonder why your loop only displays 1 column. That would be because you have said in the query to just get 1 column.
If you changed the query's 2nd parameter to null, it would get all columns.
At a guess you want to return an array of all places.
Assuming this then :-
// get Cursor with all rows(3rd parm null) for the place1 column (2nd parm)
c = db.query("rates_table", columns, null, null, null, null, null);
// Create String array according to the number of rows returned.
String[] places = new String[c.getCount()];
// loop through all rows setting the respective places element with the
// value obtained from the Cursor
while (c.moveToNext) {
places[c.getPosition()] = csr.getString(csr.getColumnIndex("place1"));
}
csr.close(); // Should always close a Cursor
return places;

Changing order of listview results from SQlite

I have a listview in my application that displays records according to the primary key _ID field with the lowest _ID number first. How can I change that so it is the highest _ID number first in the listview? i.e reverse the order.
The db query currently generating the listview is below. Thanks!
public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SLOC, DatabaseHelper.FLOC, DatabaseHelper.DSNM, DatabaseHelper.SDATE, DatabaseHelper.STIME };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
use this query:
Cursor c = mDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
You can use rawQuery method to hit any custom query like this and add ORDER BY ASC or DESC as you wish.
public Cursor fetch() {
String queryString = "SELECT * FROM tablename ORDER BY _id DESC"
Cursor cursor = sqLiteDatabase.rawQuery(queryString);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}

adding DISTINCT keyword to query() with SQLite in 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;
}

Android SQLiteDatabase: Reading one column

I have a one row database just for saving app data. My goal is to read one column (one value) from it.
This query returns all the columns in a Cursor:
public Cursor readAll() {
return getReadableDatabase().query(tableName, null, null, null, null, null, null);
}
It returns a Cursor with one row in it, just perfect. However, I don't want to read all columns at once, because it's slow as I have blob's in db too.
Instead, I'd like to read just one column at a time, separately. For example, for a column called "TEXT" it would be this:
public Cursor readText() {
String[] projection = new String[]{"TEXT"};
return getReadableDatabase().query(tableName, projection, null, null, null, null, null);
}
However, this won't work, as I get back a Cursor with zero rows.
So, how to read a specific column from SQLiteBatabase in Android?
public Cursor readText() {
return getReadableDatabase().rawQuery("SELECT colName FROM myTable", new String[] {});
}
Syntax seems to be correct. Check please that you use right name of the column. Showing the table generation code and actual query code could help.
You can use this one also
public Cursor readText() {
return getReadableDatabase().rawQuery("SELECT column_name FROM table_name", null);
}

How do I get the _count in my content provider?

What should I do to get my content provider to return the _count column with the count of records? The documentation says it is automatic, but maybe it's only taking about some built-in content provider. Running a query to the database seems not to return it.
If you are using contentProvider then you have to do it like count(*) AS count.
If you use cursor.getCount(), that would not be as efficient as the above approach. With cursor.getCount() you are fetching all the records just to get counts. The entire code should look like following -
Cursor countCursor = getContentResolver().query(CONTENT_URI,
new String[] {"count(*) AS count"},
null,
null,
null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
The reason why this works is because android needs a column name to be defined.
If you are using ContentProvider.query() a Cursor is returned. Call Cursor.getCount() to get a count of records in the returned cursor.
I had a similiar problem and found this worked for me. In the example below I wanted to get the count of images from the MediaStore provider.
final String[] imageCountProjection = new String[] {
"count(" + MediaStore.Images.ImageColumns._ID + ")",
};
Cursor countCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
imageCountProjection,
null,
null,
null);
countCursor.moveToFirst();
int existingImageCount = countCursor.getInt(0);
With cursor.getCount() you can not assure that it returns the real number of items returned. There are much better ways:
1- If you are using Content Providers, you can do a query and use the Column (_COUNT) included in BaseColumns for your projection
#Override
public Cursor query(SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
...
projection = new String[] {
ContentContract.NotificationCursor.NotificationColumns._COUNT,
};
...
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder);
return cursor;
}
2- To do a rawQuery using SELECT COUNT(*) as #saurabh says in his response.

Categories

Resources