I frequently see code which involves iterating over the result of a database query, doing something with each row, and then moving on to the next row. Typical examples are as follows.
Cursor cursor = db.rawQuery(...);
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
...
cursor.moveToNext();
}
Cursor cursor = db.rawQuery(...);
for (boolean hasItem = cursor.moveToFirst();
hasItem;
hasItem = cursor.moveToNext()) {
...
}
Cursor cursor = db.rawQuery(...);
if (cursor.moveToFirst()) {
do {
...
} while (cursor.moveToNext());
}
These all seem excessively long-winded to me, each with multiple calls to Cursor methods. Surely there must be a neater way?
The simplest way is this:
while (cursor.moveToNext()) {
...
}
The cursor starts before the first result row, so on the first iteration this moves to the first result if it exists. If the cursor is empty, or the last row has already been processed, then the loop exits neatly.
Of course, don't forget to close the cursor once you're done with it, preferably in a finally clause.
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}
If you target API 19+, you can use try-with-resources.
try (Cursor cursor = db.rawQuery(...)) {
while (cursor.moveToNext()) {
...
}
}
The best looking way I've found to go through a cursor is the following:
Cursor cursor;
... //fill the cursor here
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// do what you need with the cursor here
}
Don't forget to close the cursor afterwards
EDIT: The given solution is great if you ever need to iterate a cursor that you are not responsible of. A good example would be, if you are taking a cursor as argument in a method, and you need to scan the cursor for a given value, without having to worry about the cursor's current position.
I'd just like to point out a third alternative which also works if the cursor is not at the start position:
if (cursor.moveToFirst()) {
do {
// do what you need with the cursor here
} while (cursor.moveToNext());
}
Below could be the better way:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
//your code to implement
cursor.moveToNext();
}
}
cursor.close();
The above code would insure that it would go through entire iteration and won't escape first and last iteration.
How about using foreach loop:
Cursor cursor;
for (Cursor c : CursorUtils.iterate(cursor)) {
//c.doSth()
}
However my version of CursorUtils should be less ugly, but it automatically closes the cursor:
public class CursorUtils {
public static Iterable<Cursor> iterate(Cursor cursor) {
return new IterableWithObject<Cursor>(cursor) {
#Override
public Iterator<Cursor> iterator() {
return new IteratorWithObject<Cursor>(t) {
#Override
public boolean hasNext() {
t.moveToNext();
if (t.isAfterLast()) {
t.close();
return false;
}
return true;
}
#Override
public Cursor next() {
return t;
}
#Override
public void remove() {
throw new UnsupportedOperationException("CursorUtils : remove : ");
}
#Override
protected void onCreate() {
t.moveToPosition(-1);
}
};
}
};
}
private static abstract class IteratorWithObject<T> implements Iterator<T> {
protected T t;
public IteratorWithObject(T t) {
this.t = t;
this.onCreate();
}
protected abstract void onCreate();
}
private static abstract class IterableWithObject<T> implements Iterable<T> {
protected T t;
public IterableWithObject(T t) {
this.t = t;
}
}
}
import java.util.Iterator;
import android.database.Cursor;
public class IterableCursor implements Iterable<Cursor>, Iterator<Cursor> {
Cursor cursor;
int toVisit;
public IterableCursor(Cursor cursor) {
this.cursor = cursor;
toVisit = cursor.getCount();
}
public Iterator<Cursor> iterator() {
cursor.moveToPosition(-1);
return this;
}
public boolean hasNext() {
return toVisit>0;
}
public Cursor next() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// }
cursor.moveToNext();
toVisit--;
return cursor;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Example code:
static void listAllPhones(Context context) {
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
for (Cursor phone : new IterableCursor(phones)) {
String name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("name=" + name + " phoneNumber=" + phoneNumber);
}
phones.close();
}
The Do/While solution is more elegant, but if you do use just the While solution posted above, without the moveToPosition(-1) you will miss the first element (at least on the Contact query).
I suggest:
if (cursor.getCount() > 0) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
<do stuff>
}
}
The cursor is the Interface that represents a 2-dimensional table of any database.
When you try to retrieve some data using SELECT statement, then the database will 1st create a CURSOR object and return its reference to you.
The pointer of this returned reference is pointing to the 0th location which is otherwise called as before the first location of the Cursor, so when you want to retrieve data from the cursor, you have to 1st move to the 1st record so we have to use moveToFirst
When you invoke moveToFirst() method on the Cursor, it takes the cursor pointer to the 1st location. Now you can access the data present in the 1st record
The best way to look :
Cursor cursor
for (cursor.moveToFirst();
!cursor.isAfterLast();
cursor.moveToNext()) {
.........
}
if (cursor.getCount() == 0)
return;
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
// do something
cursor.moveToNext();
}
cursor.close();
Initially cursor is not on the first row show using moveToNext() you can iterate the cursor when record is not exist then it return false,unless it return true,
while (cursor.moveToNext()) {
...
}
Related
I want to get values but the function always returns null. Even though I debug and there is value inside variable rv.
This is my method:
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
Cursor c = db.rawQuery("select * from reviews where IDRE="+id, null);
if(c.moveToFirst() || c.getColumnCount()==1) {
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
}
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}
Some logging would help determine if you're throwing an error and ending up in that catch block, as #Daniel Nugent is saying.
But I think the issue is with your if expression. c.moveToFirst is going to move your cursor to the first row of your data source, and then return true unless that data source is empty, so the only time that if block does not occur is when your data source is empty. The only way c.getColumnCount()==1 is having any effect on the evaluation of your expression is if you have a table with only one column and no rows. Let us know what you're trying to achieve with that, and add some logging, and we'll be better able to help you.
I have edited your code ...and given two example , you can refer any one...
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
Cursor c = db.rawQuery("select * from reviews where IDRE="+id, null);
if(c==null)
return null;
c.moveToFirst();
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}
Second way:
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
String[] columns=new String[]{"IDRE","ID_FK","DATE","TYPE","COST","SERVICE","ATMOSPHERE","OVERALL","COMMENT"};
Cursor c=sql_db.query("reviews", columns, "IDRE"+"=?", new String[] {String.valueOf(id)}, null, null, null);
if(c==null)
return null;
c.moveToFirst();
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}
I'm confused about whether to use MergeCursor or CursorJoiner.
I have a Cursor (A) with a load of data in it. Lets say there are 100 rows in Cursor (A) and 3 columns. What I want to do is insert (append) a new column to the Cursor so the resulting Cursor (B) has 100 rows but 4 columns.
At this moment in time I would like the 4th column to contain a default value for the 100 rows.
How would I do this?
You can use the Decorator pattern here.
For this, Android has CursorWrapper , which is a...
Wrapper class for Cursor that delegates all calls to the actual cursor object. The primary use for this class is to extend a cursor while overriding only a subset of its methods.
Suppose your new column is called newColumn, and that it is of type String then you can do something along these lines:
class MyCursorWrapper extends CursorWrapper {
private final String NEW_COLUMN = "newColumn";
#Override
public int getColumnCount() {
// Count the virtual column in
return getWrappedCursor().getColumnCount() + 1;
}
#Override
public int getColumnIndex(String columnName) {
// Return the virtual column if they are asking for it,
// otherwise just use the original
if (columnName != null && columnName.equals("newColumn") {
return getWrappedCursor().getColumnCount();
}
return mCursor.getColumnIndex(columnName);
}
public int getColumnIndexOrThrow(String columnName)
throws IllegalArgumentException {
// Same logic as getColumnIndex()
if (columnName != null && columnName.equals(NEW_COLUMN) {
return getWrappedCursor().getColumnCount();
}
return getWrappedCursor.getColumnIndexOrThrow(columnName);
}
#Override
public String getColumnName(int columnIndex) {
if (columnIndex == getWrappedCursor.getColumnCount()) {
return NEW_COLUMN;
}
return getWrappedCursor().getColumnName(columnIndex);
}
#Override
public String[] getColumnNames() {
// Add our virtual column to the result from the original Cursor
String original = getWrappedCursor().getColumnNames()
String result = new String[original.length + 1];
System.arrayCopy(original, 0, result, 0, original.length);
result[original.length] = NEW_COLUMN;
return result;
}
#Override
public String getString(int columnIndex) {
// For the last column, return whatever you need to return here
// For real columns, just delegate to the original Cursor
if (columnIndex == getWrappedCursor().getColumnCount()) {
return yourResultHere();
}
return getWrappedCursor().getString(columnIndex);
}
}
In my code, when cursor is null i encounter the exception of CursorIndexOutOfBoundsException Index 0 requested, with a size of 0 in Android
How can I fix this problem??
public Cursor getCustAccount(long custRef){
openReadable();
Cursor cursor;
cursor = database.rawQuery(" SELECT CustAccountId AS _id,AccountNo as AccountNo,BankName as BankName,BranchName as BranchName FROM tblCustAccount WHERE CustRef =" + custRef , null);
if (cursor != null)
cursor.moveToFirst();
return cursor;
}
public ArrayList<String> getCustAccountString(long custRef) {
Cursor cursor = getCustAccount(custRef);
ArrayList<String> listAccount = new ArrayList<String>();
do {
listAccount.add(String.valueOf(cursor.getInt(1)));
} while(cursor.moveToNext());
return listAccount;
}
There's no data in the cursor. You should check that moveToFirst() succeeds before any of the get...() calls:
if (cursor.moveToFirst()) {
do {
listAccount.add(String.valueOf(cursor.getInt(1)));
} while(cursor.moveToNext());
}
use:-
if(cursor != null && cursor.moveToFirst()){
return cursor;
}
return null;
public abstract boolean moveToFirst ()
Move the cursor to the first row.
This method will return false if the cursor is empty.
Returns
whether the move succeeded.
try following code:
if (cursor.getCount() > 0) {
do {
listAccount.add(String.valueOf(cursor.getInt(1)));
} while(cursor.moveToNext());
}
I use a content provider/resolver, have a separate project/lib that provides a number of DB helper methods. I have a second project/lib that does handy things with a cursor.
Imagine as such DB Helper Method (com.example.DBHelper):
public String[] dumpColumnTable() {
Cursor cursor = cr.query(MY_URI,
new String[] { FIELD },
null,
null,
null
);
return UtilMethods.createArrayFromCursor(cursor);
}
Then the Util methods (com.example.UtilMethods):
public static String[] createArrayFromCursor(Cursor cursor) {
return createArrayFromCursor(cursor, 0);
}
public static String[] createArrayFromCursor(Cursor cursor, int column) {
if (cursor == null) return null;
String[] strings = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int i=0;
do {
strings[i] = cursor.getString(column);
i++;
} while (cursor.moveToNext());
}
return strings;
}
Obviously the cursor isn't closed. This will leak a cursor. Logcat will give you that message.
SO, close it in the inner util function:
public static String[] createArrayFromCursor(Cursor cursor, int column) {
if (cursor == null) return null;
String[] strings = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int i=0;
do {
strings[i] = cursor.getString(column);
i++;
} while (cursor.moveToNext());
}
cursor.close();
return strings;
}
But logcat will still claim the cursor wasn't closed before finalize.
If instead, in the DB Helper method, I save the return value, close the cursor, then return it, I get no cursor leak/logcat message:
public String[] dumpColumnTable() {
Cursor cursor = cr.query(MY_URI,
new String[] { FIELD },
null,
null,
null
);
String[] toret = UtilMethods.createArrayFromCursor(cursor);
cursor.close();
return toret;
}
Why ? In debugging, the cursor is marked as close when the calls return. The call stack goes from my activity->db helper->util methods. The db helper and util methods are in separate projects from the activity.
Is there some pass by reference/value issue I'm missing, or crossing multiple JAR boundaries, or the casting of what is a SQLiteCursor to the generic Cursor type that I'm missing ?
I've implemented a custom Adapter for a ExpandableListView which I extended from the CursorTreeAdapter class. Everything is working as expected.
But I'm wondering if there's pattern or some kind of best practice on how to asynchronously query the database in the getChildrenCursor() method of the adapter class. At the moment I'm passing my SQLiteOpenHelper class to the constructor of my adapter and use it in getChildrenCursor() to query the database synchronously on the UI thread.
You could also use a CursorLoader instead of subclassing AsyncTask to asynchronously query a provider.
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (id != -1) {
// child cursor
return new CursorLoader(getActivity(), childrenUri,
CHILDREN_PROJECTION, selection, selectionArgs, sortOrder);
} else {
// group cursor
return new CursorLoader(getActivity(), groupsUri,
GROUPS_PROJECTION, selection, null, sortOrder);
}
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
int id = loader.getId();
if (id != -1) {
// child cursor
if (!data.isClosed()) {
try {
mAdapter.setChildrenCursor(id, data);
} catch (NullPointerException e) {
Log.w("TAG",
"Adapter expired, try again on the next query: "
+ e.getMessage());
}
}
} else {
// group cursor
mAdapter.setGroupCursor(data);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
int id = loader.getId();
if (id != -1) {
// child cursor
mAdapter.setChildrenCursor(id, null);
} else {
// group cursor
mAdapter.setGroupCursor(null);
}
}
And in your adapter class you can override the getChildrenCursor() method like this:
protected Cursor getChildrenCursor(Cursor groupCursor) {
// Given the group, we return a cursor for all the children within that group
int id = groupCursor.getInt(groupCursor
.getColumnIndex(ContactsContract.Groups._ID));
mActivity.getLoaderManager().initLoader(id, null,mFragment);
return null;
}
getChildrenCursor says:
If you want to asynchronously query a
provider to prevent blocking the UI,
it is possible to return null and at a
later time call setChildrenCursor(int,
Cursor).
So, in getChildrenCursor(), start an AsyncTask and return null. In the onPostExecute() method call setChildrenCursor()