VolodymyrH VolodymyrH - 1 year ago 76
Android Question

Method in onCreate runs only after device rotation

My

Activity
uses
RecyclerView
to show a list of data. This data downloads some
Moview
s using a
AsyncTaskLoader
. I initialise the loader in
onCreate
but when I run it I see nothing. But if I click the button to rotate the device I see data. I tried to put this method to other lifecycle methods, but still the same. And logs are the same all the time.

@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);
}


My loader:

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();
}

Answer Source

use notifyDataSetChanged();

@Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
    mMovieAdapter.clear();
    if (data != null && !data.isEmpty()) {
        mMovieAdapter.addAll(data);
        mMovieAdapter.notifyDataSetChanged()
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download