简体   繁体   中英

savedinstancestate an arraylist an restore it to recyclerview

i have 1 activity and 3 fragments, i load data from API on the fragment. what i want is, when my phone orientation get changed, my fragment doesnt load the data from the API. but how can i save the instance? here is my fragment

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

I've tried using savedInstance and configurationChanged, maybe how im use id is wrong. and sorry to my bad english. Thanks

One solution can be using Architecture Components , more precisely LiveData and ViewModel , the first sentence of the ViewModel 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM