Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getLastVisiblePosition returning -1

I'm having a problem with my ListView (using CursorAdapter). When I call getListView().getLastVisiblePosition() I am receiving -1. This is a problem since my list is populated with items. Additionally, getListView().getFirstVisiblePosition() always returns 0, no matter where I am scrolled on the list. Any ideas?

It has something to do with startManagingCursor

    @Override
    public void changeCursor(Cursor cursor) {
        super.changeCursor(cursor);
        MyActivity.this.mCursor = cursor;
        //startManagingCursor(MyActivity.this.mCursor);
    }

If I comment out startManagingCursor, everything works fine. I've also tried adding stopManagingCursor() before changing the Cursor and still have the same problem.

like image 227
Andrew Avatar asked Oct 27 '10 19:10

Andrew


2 Answers

This is because the moment you call getListView().getLastVisiblePosition() the listview is not rendered. You can add the call to the view's message queue like this:

listview.post(new Runnable() {
    public void run() {
        listview.getLastVisiblePosition();
    }
});
like image 132
luciferleo Avatar answered Oct 14 '22 00:10

luciferleo


Even I faced the same problem. The thing is that, getLastVisiblePosition() works only when you are in the first element of your listview and for the rest you will get null being returned. So what I did is that, I made a small calculation to find out the exact view position which I have mentioned below,

int  LastPos=(mylist.getLastVisiblePosition()-mylist.getFirstVisiblePosition());

This returns the exact last position without a doubt.

like image 45
Andro Selva Avatar answered Oct 13 '22 23:10

Andro Selva