onCreate中的方法仅在设备轮换后运行

时间:2017-08-16 09:50:27

标签: android loader asynctaskloader

我的Activity使用RecyclerView来显示数据列表。此数据使用Moview下载了一些AsyncTaskLoader个。我在onCreate中初始化了加载器,但是当我运行它时,我什么都没看到。但是,如果我单击按钮旋转设备,我会看到数据。我试图将此方法用于其他生命周期方法,但仍然相同。而且日志一直都是一样的。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movie);

    mMovieListRecyclerView = (RecyclerView) findViewById(R.id.rv_movieList);
    mGridLayoutManager = new GridLayoutManager(this, 2);
    mMovieListRecyclerView.setLayoutManager(mGridLayoutManager);
    mMovieAdapter = new MovieAdapter(this, new ArrayList<Movie>());
    mMovieListRecyclerView.setAdapter(mMovieAdapter);
    initialiseLoader();
}

private void initialiseLoader() {
    ConnectivityManager connectivityManager = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        LoaderManager loaderManager = getLoaderManager();
        loaderManager.initLoader(MOVIE_LOADER_ID, null,  MovieActivity.this);
    }

我的装载机:

public class MovieLoader extends AsyncTaskLoader<List<Movie>> {

private static final String LOG_TAG = MovieLoader.class.getName();

private String mURL;

public MovieLoader(Context context, String url) {
    super(context);
    mURL = url;
}

@Override
protected void onStartLoading() {
    forceLoad();
}

@Override
public List<Movie> loadInBackground() {
    if (TextUtils.isEmpty(mURL)) {
        return null;
    }

    return QueryUtils.fetchMovieData(mURL);
}

    @Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
    mMovieAdapter.clear();
    if (data != null && !data.isEmpty()) {
        mMovieAdapter.addAll(data);
    }
}

@Override
public void onLoaderReset(Loader<List<Movie>> loader) {
    mMovieAdapter.clear();
}

1 个答案:

答案 0 :(得分:1)

使用notifyDataSetChanged();

@Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
    mMovieAdapter.clear();
    if (data != null && !data.isEmpty()) {
        mMovieAdapter.addAll(data);
        mMovieAdapter.notifyDataSetChanged()
    }
}