How can this fragment preserve state upon rotation
NickName:Marc Ask DateTime:2017-10-12T10:58:39

How can this fragment preserve state upon rotation

I'm experimenting with fragments. I have MainActivity consisting of a framelayout that swaps in fragments(master "SearchFragment" and detail "LyricsFragment"):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FragmentManager fragmentManager = getSupportFragmentManager();

    int index = fragmentManager.getBackStackEntryCount() - 1;
    if (index == -1) {
        fragmentManager.beginTransaction()
                .replace(R.id.placeholder, new SearchFragment(), SEARCH)
                .commit();
    } else {
        FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(index);
        String tag = backEntry.getName();
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment != null) {
            fragmentManager.beginTransaction()
                    .replace(R.id.placeholder, fragment)
                    .commit();
        }
    }
}

I use https://github.com/frankiesardo/icepick to save state of my SearchFragment in an arrayList:

public class SearchFragment extends Fragment {

    @Inject CompositeSubscription subscriptions;

    @BindView(R.id.search_field) EditText searchField;
    @BindView(R.id.recyclerview) RecyclerView recyclerView;

    @State ArrayList<Track> tracks = new ArrayList<>();
    private TrackAdapter adapter;
    private TrackClickListener listener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof  TrackClickListener) {
            listener = (TrackClickListener) context;
        } else {
            throw new IllegalArgumentException("context must be of type TrackClickListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);
        bindViews(view);

        adapter = new TrackAdapter(listener, picasso);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), COLS));
        recyclerView.setAdapter(adapter);
        Log.d("TRACK", "tracks.size=" + tracks.size());
        adapter.setAdapterItems(tracks);
        return view;
    }

    @VisibleForTesting
    void onSearchSuccess(ArrayList<Track> tracks) {
        this.tracks = tracks;
        adapter.setAdapterItems(tracks);
    }

    @OnClick(R.id.search_button)
    void onSearchClick() {
        searchTracks();
    }

    private void searchTracks() {
        subscriptions.add(api.searchTracks(searchTerm)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SearchResult>() {

                    @Override
                    public void onCompleted() {}
                    @Override
                    public void onError(Throwable e) {}

                    @Override
                    public void onNext(SearchResult searchResult) {
                        onSearchSuccess(searchResult.getResults());
                    }
                }));
    }

public interface TrackClickListener {
    void startDetailScreen(Track track);
}
}

Can someone explain why the log statement prints this on rotation:

tracks.size=20 ----ROTATE SCREEN---- tracks.size=20 tracks.size=0

The list is preserved at first but ends up being cleared. How can I preserve the populated recyclerview after i rotate? The library I am using avoids the boilerplate of saveInstanceState. I expected my list to be saved and the adapter to be reset with it when the device is rotated.

Copyright Notice:Content Author:「Marc」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46700704/how-can-this-fragment-preserve-state-upon-rotation

More about “How can this fragment preserve state upon rotation” related questions

How can this fragment preserve state upon rotation

I'm experimenting with fragments. I have MainActivity consisting of a framelayout that swaps in fragments(master "SearchFragment" and detail "LyricsFragment"): @Override protected void onCreate(B...

Show Detail

Unknown fragment after rotation

In my application I create a fragment with the keyword new and set it by FragmentTransaction. Upon rotation a stumbled upon a NullPointerException in the method onActivityCreated() indicating a mis...

Show Detail

Fragment not destroyed on rotation

I have a fragment which is added programmatically. I have however discovered that after a rotation, a new fragment is created but the old fragment is still alive (though not being displayed) I assu...

Show Detail

Saving an activity's/fragment's state

Let's assume I have an activity inside of which I have one fragment (and only one fragment). I want to preserve the fragment's state in case of rotation. I have two options: Option A) Preserving ...

Show Detail

Fragment View State on Screen Rotation

I have a few fragments that are loaded when a user clicks on an item in a list. Say a user has clicked on second item in the list, loading the second fragment. But, upon rotating, the screen, the f...

Show Detail

Prevent EditText from focussing after rotation

I've implemented a simple EditText that provides a Done button to hide the keyboard and upon rotating to landscape it does not present a full screen dialog for the EditText. But there's a problem. ...

Show Detail

How can I lock Fragment rotation

How can I lock one (and only one) Fragment to rotate on my tablet version ? I'm using a Fragment lib for my qrcode scanner but I do not know why this one is rotating but don't adapte the camera vi...

Show Detail

How do I preserve uri fragment in safari upon redirect?

My gwt / gae application utilizes activities and places. In order to create asynchronous processes (such as resetting a password or verifying ownership of an email address) I use a pattern where an

Show Detail

How do I preserve a web view's display state across activity destruction?

I'm making an Android app that's a complex javascript app embedded in a web view. The web view refreshes every time the main activity's destroyed (ie due to rotation, back button press, etc). To

Show Detail

Fragment Menu disappears upon rotation

I have a menu added by a fragment in onCreateOptionsMenu(). When the fragment first appears the appropriate icons appear in the ActionBar and Pressing the menu key or the overflow icon shows the

Show Detail