1

I'm once more struggling with ParseQueryAdapter when pagination is enabled.

I have a ListView with a ParseQueryAdapter, displaying me the correct list. But as I do not know how many elements this list would count, I enable pagination in the adapter by

setPaginationEnabled(true);

When I click on an item of the list, it makes a transaction with another fragment, let say B. When I tap back, the ListView fragment comes back (fragment A).

fragment A contains list with items. OnItemClick -> fragment B

Because I have pagination but I don't want the user to notice it, I load automatically the next page when I reach the end of a page by :

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    getListView().setAdapter(adapter);
    getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            final int lastItem = firstVisibleItem + visibleItemCount;
            if (lastItem == totalItemCount) {
                if (preLast != lastItem) { //this avoid multiple calls for the last item
                    preLast = lastItem;
                    adapter.loadNextPage();
                }
            }
        }
    });
}

The problem is that when the user click on an item in the list, and press back once B appears, it comes back to A, but the fragment lost his state, I have to scroll again to come back where the item I clicked on was.

I am right now trying to restore A state by counting the pages I loaded, then load it manually with something like that:

@Override
public void onResume() {

    // mLoadedPages is initialized with 0 and 
    // is incremented each time I load a page

    if (mLoadedPages != 0) {
        for (int i = 0; i < mLoadedPages; i++) {
            adapter.loadNextPage();
        }

        getListView().setSelection(mLastKnownFirstItem);
    }
    super.onResume();
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("mLoadedPages", mLoadedPages);
    savedInstanceState.putInt("mLastKnownFirstItem", getListView().getFirstVisiblePosition());
}

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    if (savedInstanceState != null) {
        mLoadedPages = savedInstanceState.getInt("mLoadedPages");
        mLastKnownFirstItem = savedInstanceState.getInt("mLastKnownFirstItem");
    }
}

This seems extremely rude, brutal and not elegant at all (and it also gaves me IndexOutOfBoundsException with this code). Does someone know how I can get rid of this problem?

Thank you in advance.

Nebneb
  • 114
  • 8

0 Answers0