Prof
Prof

Reputation: 706

How to get cursor count without LIMIT?

I have a ListView set up from a cursor that grabs the first 10 rows in a database (LIMIT).

    cursor = db.query("MYTABLE",
            new String[]{"_id", "NUMBER", "NAME"}, null, null, null, null, null, "10");

The list is set up to "infinitely scroll". It does this by comparing the number of items in the list and the number of items in the database once a scroll completes (onScroll from OnScrollListener)

    public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    ListView listView = (ListView) findViewById(R.id.my_list);

                    long numberOfItemsInDB = DatabaseUtils.queryNumEntries(db, "MYTABLE");
                    long numberOfItemsInList = listView.getAdapter().getCount();
                    long difference = numberOfItemsInDB - numberOfItemsInList;

                    if (difference > 0) {
                    ... //do stuff here 
                    }

This works. But sometimes the list may be populated with items from a custom cursor (from search filtering for example) and so I would need the item count of that cursor. I can have a consistent count by using .getCount() but if I have already used LIMIT then it will just return the LIMIT I had which was 10.

How can I get the number of items in a cursor ignoring the limit?

Upvotes: 0

Views: 312

Answers (1)

Dhaval Patel
Dhaval Patel

Reputation: 10299

Use below method to get Row Count in table.

public synchronized long getRowCount(String TABLE_NAME) {
    SQLiteDatabase db = this.getReadableDatabase();
    return DatabaseUtils.queryNumEntries(db, TABLE_NAME);
}

To get the Table row count with where clause

public synchronized long getRowCount(String TABLE_NAME) {
    SQLiteDatabase db = this.getReadableDatabase();
    return DatabaseUtils.queryNumEntries(db, TABLE_NAME, "NAME like ?", new String[]{"%D%"})
}

Upvotes: 0

Related Questions