st1hy st1hy - 1 year ago 82
Android Question

How to select position of new row in database after query?

I am using recycler view to display table content with filters, sorting etc. When adding new item I insert new item, query database for new cursor using SELECT with ordering.

In recycler view it is suggested that I should call in that case notifyItemInserted(int position) with position meaning position in cursor of new item.

There are 2 things I know I can do:

  1. iterate cursor and find position of the item (witch is maybe not the best idea if my table have lost of rows)

  2. don't notifyItemInserted, but instead notifyDataSetChanged and live without nice animation (like a savage)

My question is is it possible to perform a sql query that will do something like this:

  1. Query what I want

  2. Add COLUMN_POSITION that enumerate results of the previous query (in memory)

  3. Query the above with select COLUMN_POSITION where id = id of new item.

  4. Get a cursor with position

Bonus questions: are there any other solutions to this problem? How to find a position of new item that I know in cursor?

Answer Source

I finally got to the conclusion that this idea is unnecessary complicated and actually iterating over cursor is good enough.

CursorJoiner internally but compares cursors with little more restrictive behaviour. If you want to use descending order or have not unique columns the behaviour is undefined so you're out of luck.

 * @return position of new item or -1 if item could not be found inside the cursor
private int getNewItemPosition(@NonNull Cursor cursor, @NonNull Tag dao) {
    int idColumn = cursor.getColumnIndexOrThrow(TagDao.Properties.Id.columnName);
    long newDaoId = dao.getId();
    while (cursor.moveToNext()) {
        if (newDaoId == cursor.getLong(idColumn)) {
            return cursor.getPosition();
    return -1;

My initial objection about performance did not turned out to be valid at least at scale that android apps are using and as wise masters said don't optimize something unless tests show its a problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download