No matter which example from stackoverflow I choose to follow I don't get the desired result.
I want to save recyclerView scroll position on rotation but the save of state of the selection (TOP RATED MOVIES, FAVORITE MOVIES AND POPULAR MOVIES )
seems to override the state to reload the desired selection but from the the top of the screen .
E.g. half way or all the way at the bottom of the, then , rotated it saves the selection type (e.g. whatever it was displaying before rotation) but loads from the start again(the top(this is not desired , I need to stay at the same position)).
my code:
MainActivity
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final int POP = 1;
public static final int TOP = 2;
public static final int FAV = 3;
int selection = -1;
private RecyclerView rv;
private MovieAdapter adapter;
private MovieDbHelper dbHelper;
private FrameLayout frame;
private AppCompatActivity activity = MainActivity.this;
private static final String BUNDLE_RECYCLER_LAYOUT = "classname.recycler.layout";
public static int index = -1;
public static int top = -1;
int currentVisiblePosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isOnline()) {
Toast.makeText(activity, "No Connection", Toast.LENGTH_SHORT).show();
} else {
initControls();
dbHelper = new MovieDbHelper(activity);
if (savedInstanceState != null) {
selection = savedInstanceState.getInt("selection");
//Now just load the list
switch (selection) {
case POP:
loadJSON(POP);
break;
case TOP:
loadJSON(TOP);
break;
case FAV:
initializeFavorites();
break;
case -1:
initializeViews();
break;
}
} else {
initializeViews();
}
}
}
private void initControls() {
rv = findViewById(R.id.rv_main);
adapter = new MovieAdapter(this, new ArrayList<Movie>());
rv.setLayoutManager(new GridLayoutManager(this, ScreenSizeUtil.calculateNoOfColumns(this)));
rv.setItemAnimator(new DefaultItemAnimator());
rv.setAdapter(adapter);
dbHelper = new MovieDbHelper(activity);
frame = findViewById(R.id.frame);
checkSortOrder();
}
private void initializeViews() {
Toast.makeText(this, "Change sort order via the Settings Menu....", Toast.LENGTH_SHORT).show();
}
private void initializeFavorites() {
getAllFavorites();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private void loadJSON(int listType) {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(this, "Error with Api Key....", Toast.LENGTH_SHORT).show();
return;
}
Client Client = new Client();
Service apiService =
Client.getClient().create(Service.class);
Call<MovieResponse> call = listType==TOP? apiService
.getMovies("top_rated",BuildConfig.THE_MOVIE_DB_API_TOKEN): apiService.getMovies("popular",BuildConfig.THE_MOVIE_DB_API_TOKEN) ;
call.enqueue(new Callback<MovieResponse>() {
@Override
public void onResponse(Call<MovieResponse> call, final Response<MovieResponse> response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
List<Movie> movies = response.body().getResults();
adapter.setMovieList(movies);
rv.scrollToPosition(0);
}
});
}
@Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
Toast.makeText(MainActivity.this, "Error with Data!", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(BUNDLE_RECYCLER_LAYOUT, rv.getLayoutManager().onSaveInstanceState());
}
private void checkSortOrder(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String sortOrder = preferences.getString(
this.getString(R.string.pref_sort_order_key),
this.getString(R.string.pref_most_popular)
);
if (sortOrder.equals(this.getString(R.string.pref_most_popular))) {
Log.d(TAG, "Sorting by most popular");
loadJSON(POP);
} else if (sortOrder.equals(this.getString(R.string.pref_highest_rated))){
Log.d(TAG, "Sorting by Top rated");
loadJSON(TOP);
} else{
Log.d(TAG, "Sorting by Favorites");
initializeFavorites();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
(rv.getLayoutManager()).scrollToPosition(currentVisiblePosition);
currentVisiblePosition = 0;
}
@Override
public void onPause() {
super.onPause();
currentVisiblePosition = 0;
currentVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();}
private void getAllFavorites() {
new AsyncTask<Void, Void, ArrayList<Movie>>() {
@Override
protected ArrayList<Movie> doInBackground(Void... voids) {
return new ArrayList<>(dbHelper.getAllFavorites());
}
@Override
protected void onPostExecute(ArrayList<Movie> aVoid) {
super.onPostExecute(aVoid);
adapter.setMovieList(aVoid);
}
}.execute();
}
}
Any advice would be great please recognise the slight difference from How to save scroll position of RecyclerView in Android?.
Thanks Ben