如何在onSaveInstanceState上存储recyclerview数据 [英] how to store recyclerview data on onSaveInstanceState

查看:139
本文介绍了如何在onSaveInstanceState上存储recyclerview数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将API中的数据保存在RecyclerView中,以便在旋转屏幕时不重新加载

I want to save data from the API in the RecyclerView so that when rotating the screen is not reloaded

我认为我可以使用onSaveInstanceState,但仍然不太了解如何使用它

I think I can use onSaveInstanceState but still don't really understand how to use it

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final RecyclerView rvTVShow = view.findViewById(R.id.rv_shows);
    rvTVShow.setHasFixedSize(true);
    rvTVShow.setLayoutManager(new LinearLayoutManager(getActivity()));

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);
    Call<MovieResponse> call = apiService.getTVShow(API_KEY);
    call.enqueue(new Callback<MovieResponse>() {

        @Override
        public void onResponse(@NonNull Call<MovieResponse> call, @NonNull Response<MovieResponse> response) {
            final List<Movies> movies = Objects.requireNonNull(response.body()).getResults();

           TvShowAdapter tvShowAdapter = new TvShowAdapter(movies , R.layout.list_movies);
           rvTVShow.setAdapter(tvShowAdapter);

           ....
        }

推荐答案

我将解释在重构代码时saveInstanceState的工作方式.

I will explain how savedInstanceState works while refactoring your code.

首先:创建一个全局Movie对象和一个适配器

First: Create a global Movie object and an Adapter for it

  List<Movies> movies = new ArrayList();
  TvShowAdapter tvShowAdapter = null;

在活动onCreate下重新初始化适配器

Re-initialize adapter under activity onCreate

  tvShowAdapter = new TvShowAdapter(movies , R.layout.list_movies);
       rvTVShow.setAdapter(tvShowAdapter);

创建一个处理电影的新方法数据填充

Create a new method to handle movie data population

 public void populateRV(List<Movies> movies)
{
      this.movies = movies;
   //notify adapter about the new record
      tvShowAdapter.notifyDataSetChanged(); 
 }

在响应回调下将数据插入Movies对象

Insert data to Movies object under your Response callback

  movies = Objects.requireNonNull(response.body()).getResults();
 populateRV(movies);

每次活动的方向更改时,Android都会通过重绘所有视图的状态来重置它们.这会导致非持久性数据丢失.但是在重绘视图之前,它会调用方法 onSavedInstanceState

Everytime the orientation of an activity changes Android resets the states of all views by redrawing them. This causes non persistent data to be lost. But before redrawing views it calls the method onSavedInstanceState

因此,我们可以使用android提供的onSavedInstanceState方法保存视图状态,以防止状态丢失.

Hence we can prevent state loss by saving the state of our views using the already defined onSavedInstanceState method provided by android.

在活动的重写的onSavedInstanceState方法内添加以下代码段

Add the following block inside the overridden onSavedInstanceState method of your activity

 //this saves the data to a temporary storage
 savedInstanceState.putParcelableArrayList("movie_data", movies);
 //call super to commit your changes
 super.onSaveInstanceState(savedInstanceState);

下一步是在方向更改完成后恢复数据

Next is to recover the data after orientation change is completed

在您的活动onCreate中添加以下代码块,并确保它在初始化适配器后出现

Add the following block in your activity onCreate and make sure it comes after initializing your adapter

 //...add the recyclerview adapter initialization block here before checking for saved data

 //Check for saved data
 if (savedInstanceState != null) {
 // Retrieve the data you saved
 movies = savedInstanceState.getParcelableArrayList("movie_data");

  //Call method to reload adapter record
 populateRV(movies);
 } else {
 //No data to retrieve
//Load your API values here.
 }

这篇关于如何在onSaveInstanceState上存储recyclerview数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆