0

When / How to add a ListView Adapter, that it gets restored with back button? I want to move back from FragmentB to Fragment A and have the same Adapter as I had before going to FragmentB.

@Override
public void onViewCreated(@NonNull View view, @Nullable final Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    adapter = new UserAdapter(getContext(), R.layout.list_item, userList);
}

With this I am always creating a new one. I just want to create it once and then keep it.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
ximix424
  • 75
  • 6

2 Answers2

0

I found a solution. For anyone that has the same question:

Create a boolean inside your Fragment like this and check in which version your Fragment is. Like this you can only initially create your adapter at the beginning and not override it every time you come back.

public class MyFragment extends Fragment {
    private boolean isCreated;
    private MyAdapter adapter;

    public MyFragment() {
    // Required empty public constructor
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable final Bundle savedInstanceState) {
       super.onViewCreated(view, savedInstanceState);
       if(!isCreated){
          adapter = new MyAdapter(getContext(), R.layout.list_item, myList);
       }
       // create your listView here, set adapter and set onItemClickListener..
    }

    @Override
    public void onResume() {
       super.onResume();
       if(!isCreated)
       {
          isCreated = true;
       }
}
ximix424
  • 75
  • 6
  • Well this will work only if your Fragment instance was not destroyed. Also you don't need the boolean. You could just use onCreate instead of onViewCreated in order to instantiate the adapter only once in the lifecycle of the fragment. – Andre Dec 06 '19 at 23:57
0

The actual solution depends on your fragment transactions and the fact if your Fragment gets destroyed during the transaction or not.

If it survives after returning from the second fragment, then you can simply use an other lifecycle callback (onCreated). This way your adapter will be created only once:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adapter = new MyAdapter( ... );
}

If your fragment does not survive (if it gets replaced and destroyed), then you have to save the state of your adapter, create a new one and apply the old (saved) state to it.

Andre
  • 364
  • 2
  • 11