2

I'm wondering if there is any alternative for cursor.getCount() which is way too expensive! My goal is to run one query first, if cursor is null or cursor.getCount() <=0 then I will need to run another query.

But since the underlying data can be large, I was getting Application Not Responding for the getCount() call. any better solution to do it?

Green Ho
  • 881
  • 3
  • 14
  • 27

4 Answers4

2

If the cursor is empty, moveToFirst will be false

Hoan Nguyen
  • 18,033
  • 3
  • 50
  • 54
2

If you're only interested in finding out whether the table has any rows at all, then one very optimal query would be:

SELECT EXISTS (SELECT * FROM <tableName>);

This does not scan the entire table unlike count(), and it execute in under two milliseconds for a table with 250,000+ records on an iPhone, so it definitely scales with size.

Anurag
  • 140,337
  • 36
  • 221
  • 257
  • And then? check the count of cursor? – Darpan Sep 24 '15 at 04:14
  • @Darpan the count of the cursor for this query will always be 1. It will yield exactly one row with a value of either 0, or 1. 0 means no matching rows were found. 1 means that at least one matching row was found. – Anurag Sep 24 '15 at 04:24
1

It is very difficult to avoid using Cursor.getCount() because most (if not all?) Cursor methods eventually call it. See the source code for yourself.

Maybe try using the limit clause in the query and set the limit to 1, then checking the cursor returned from the query to see if it is empty or not?

Eric
  • 16,397
  • 8
  • 68
  • 76
0

Run the first query with limited fields. For example, the first query may run only for _id.

codeFood
  • 1,241
  • 16
  • 16
  • yes, that's what i do. i query one column only but still has the issue. is there a way we can check if the 1st row is null? – Green Ho Aug 09 '13 at 21:20
  • You can run a query to get only the 1st row with "where" clause; "_id = 0", it will get you only the first row. – codeFood Aug 10 '13 at 22:26