当前位置: 动力学知识库 > 问答 > 编程问答 >

android - CursorLoader cancelled when activity is paused

问题描述:

I have a CursorLoader that provides data to a ListFragment. I have the notification mechanism correctly configured in my ContentProvider with:

cursor.setNotificationUri(getContext().getContentResolver(), uri);

and

getContext().getContentResolver().notifyChange(uri, null)

When I select a list item, a new child Activity is opened and in the onCreate() of this Activity I do a query modifying the item details.

I know the notification is fired and the CursorLoader re-queries the content provider.

The problem I'm facing is that sometimes my CursorLoader is cancelled because the parent Activity is being paused (or stopped) and the onLoadFinished() never gets called.

When the CursorLoader is cancelled, even if I re-init the loader onResume() of the ListFragment, I can't see any change in the data:

@Override

public void onResume() {

super.onResume();

getLoaderManager().initLoader(URL_LOADER, null, this);

}

I'm using support library v4.

I'm assuming CursorLoader updates the parent Activity even when it is on background. Do I need to restart the loader when the ListFragment resumes?

(edit)

I forgot to mention that I'm creating and starting the loader from a ListFragment.

After some debugging, I found that when the ListFragment is stopped, the loader manager cancels all current loaders for the fragment.

In my case, when the new child activity is created, a db change triggers a notification that makes the loader perform a re-query. If the query does not finish before the parent fragment stops, the loader is canceled and the old cursor is still valid. When I navigate back to this parent activity with the ListFragment from the child activity, the data shown is from the old cursor. In this case, the notification is lost and I have to restart the loader onResume().

I did a test where I modified the db only after 10s since the child activity started, and because the loader was not canceled (because the parent activity was already stopped), I received a new cursor when returning to the parent activity.

Can anybody help me find a solution that does not involve a forced re-query (restartCursor()) every time the parent activity resumes?

网友答案:

When using the support library, you need to use getSupportLoaderManager() instead of getLoaderManager(), But you can only get it from the FragmentActivity. So try using this code instead:

getActivity().getSupportLoaderManager().initLoader(id, null, this);
分享给朋友:
您可能感兴趣的文章:
随机阅读: