数据未加载到片段

Data is not loaded to the Fragment

从我的 ContentProvider 获取的数据未加载到屏幕中。我不知道问题出在哪里,尤其是 onLoadFinished 中传递的数据变量不为 null 并且 ContentProvider 中的查询方法也不为 return null。这是 Loader 回调的实现。

onLoadFinished data.getCount() 中的 returns 0.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    getLoaderManager().initLoader(MOVIE_LOADER, null, this);
    super.onActivityCreated(savedInstanceState);
}

@Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
    android.support.v4.content.Loader cursorLoader;
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    pref = preferences.getString("sort_method", "0");
    String a;
    if (pref.equals("0")) {
        cursorLoader = new android.support.v4.content.CursorLoader(getActivity(), MovieContract.MostPopMovieEntry.CONTENT_URI,
                new String[]{MovieContract.MostPopMovieEntry._ID, MovieContract.MostPopMovieEntry.COLUMN_POSTER_PATH},
                null,
                null,
                null);
    } else {
        cursorLoader = new android.support.v4.content.CursorLoader(getActivity(), MovieContract.TopRatedMovieEntry.CONTENT_URI,
                new String[]{MovieContract.TopRatedMovieEntry._ID, MovieContract.TopRatedMovieEntry.COLUMN_POSTER_PATH},
                null,
                null,
                null);
    }
    if (cursorLoader != null) {
        a = "cursorLoader initiated in onCreateLoader is not null";
    } else {
        a = "cursorLoader initiated in onCreateLoader is null";
    }
    Log.d(LOG_TAG, a);

    return cursorLoader;
}

@Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        Log.d(LOG_TAG, data.getCount() + " rows loaded");
        if (data != null) {
            Log.d(LOG_TAG, "Data received onLoadfinished is no null");
        }else{
            Log.d(LOG_TAG, "Data received onLoadfinished is null");
        }
        movieAdapter.swapCursor(data);
    }

查询不return null,onCreateLoader中启动的loader不return null,onLoadFinished中收到的数据也不return ] 为空。

知道导致数据未加载到 Fragment 的问题可能是什么吗?

当适配器属于 ViewPager 时,我遇到了同样的问题

这段代码解决了我的问题

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // to be restored after reload
        mInitialScrollPosition = mViewPager.getCurrentItem();

        // do change the data
        mAdapter.swapCursor(data);

        // restore position is invalid
        if (mInitialScrollPosition >= mAdapter.getCount()) mInitialScrollPosition = -1;

        // do change the data
        mAdapter.notifyDataSetChanged();
        mViewPager.setAdapter(mAdapter);

        if (mInitialScrollPosition >= 0) mViewPager.setCurrentItem(mInitialScrollPosition);
    }

仅使用属于 GridView 的适配器

              mAdapter.notifyDataSetChanged();

有必要。