我的Activity
使用RecyclerView
来显示数据列表。此数据使用AsyncTaskLoader
下载一些Moview
。我在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();
}
使用notifyDataSetChanged();
@Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
mMovieAdapter.clear();
if (data != null && !data.isEmpty()) {
mMovieAdapter.addAll(data);
mMovieAdapter.notifyDataSetChanged()
}
}