savedinstancestate arraylist将其恢复到recyclerview

时间:2018-05-06 16:20:52

标签: android android-recyclerview

我有1个活动和3个片段,我从片段上的API加载数据。 我想要的是,当我的手机方向改变时,我的片段不会从API加载数据。 但是如何保存实例? 这是我的片段

public class NowPlayingFragment extends Fragment {

    private EditText searchMovie;
    private Button btnSearch;
    private String lang;
    ArrayList<Movie> arrayList;
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    ListView lv;
    ConstructorHelper ch;
    KeyHelper kh;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_now_playing, container, false);
        setupView(rootView);
        lang = getArguments().getString("lang");
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new ReadJSON().execute(kh.KEY_URL_NOW_PLAYING +
                        "api_key=" + kh.KEY_API +
                        "&" +
                        "language=" + lang +
                        "&" +
                        "page=1");
            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        setupClickFunction();
        return rootView;
    }

    public void setupView(View rView) {
        arrayList = new ArrayList<>();
        searchMovie = (EditText) rView.findViewById(R.id.eCari);
        btnSearch = (Button) rView.findViewById(R.id.bCari);
        mRecyclerView = (RecyclerView) rView.findViewById(R.id.list_recycler_view);
        mRecyclerView.setHasFixedSize(true);

    }

    public void setupClickFunction() {

        btnSearch.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                arrayList = new ArrayList<>();
                if (ch.isEmpty(searchMovie)) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new ReadJSON().execute(kh.KEY_URL_NOW_PLAYING +
                                    "api_key=" + kh.KEY_API +
                                    "&" +
                                    "language=" + lang +
                                    "&" +
                                    "page=1");
                        }
                    });
                } else {
                    final String query = searchMovie.getText().toString().replace(" ", "+");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new ReadJSON().execute(kh.KEY_URL_SEARCH +
                                    "api_key=" + kh.KEY_API +
                                    "&" +
                                    "language=" + lang +
                                    "&" +
                                    "query=" + query +
                                    "&" +
                                    "page=1" +
                                    "&" +
                                    "include_adult=false");
                        }
                    });
                }

            }
        });
    }

    class ReadJSON extends AsyncTask<String, Integer, String> {
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(getActivity());
            dialog.setTitle(getString(R.string.title_dialog));
            dialog.setMessage(getString(R.string.title_massage));
            dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            return ch.readURL(params[0]);
        }

        @Override
        protected void onPostExecute(String content) {
            try {
                JSONObject jsonObject = new JSONObject(content);
                JSONArray jsonArray = jsonObject.getJSONArray("results");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject movieObject = jsonArray.getJSONObject(i);
                    arrayList.add(new Movie(
                            movieObject.getString("id"),
                            movieObject.getString("poster_path"),
                            movieObject.getString("title"),
                            movieObject.getString("overview"),
                            ch.released(movieObject.getString("release_date"))
                    ));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mAdapter = new ListAdapterOnline(getActivity(), arrayList, NowPlayingFragment.this);
            mRecyclerView.setAdapter(mAdapter);

            dialog.dismiss();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            ArrayList<Movie> movies = savedInstanceState.getParcelableArrayList("movieList");
            mAdapter = new ListAdapterOnline(getActivity(), movies, NowPlayingFragment.this);
            mRecyclerView.setAdapter(mAdapter);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            ArrayList<Movie> movies = savedInstanceState.getParcelableArrayList("movieList");
            mAdapter = new ListAdapterOnline(getActivity(), movies, NowPlayingFragment.this);
            mRecyclerView.setAdapter(mAdapter);
        }
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mAdapter = new ListAdapterOnline(getActivity(), arrayList, NowPlayingFragment.this);
        mRecyclerView.setAdapter(mAdapter);
        Log.d("State","onConfigurationChanged");
    }
}

我尝试过使用savedInstance和configurationChanged,也许我是如何使用id错误的。 抱歉我的英语不好 感谢

1 个答案:

答案 0 :(得分:0)

One solution can be using Architecture Components, more precisely d1 and Base, the first sentence of the LiveData documentation says:

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

It involves learning a new concept if you are not familiar with it, but it's worth it. This article provides a great introduction. But you will probably benefit the most from the codelab, and the documentation.