数据未加载到片段

时间:2015-10-06 12:41:57

标签: android android-contentprovider android-adapter android-loadermanager

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

onLoadFinished中的data.getCount()返回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);
    }

查询没有返回null,在onCreateLoader中启动的加载器不返回null,onLoadFinished中收到的数据都不返回null。

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

1 个答案:

答案 0 :(得分:0)

当适配器属于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();

是必要的。