ArrayList gets destroyed when fragment is switched to any other fragment or if app is closed and run again

Viewed 110

In my android app, I have a navigation view which contains 5 fragments. In one fragment, I have an array list which is displayed in a list view, when I open the fragment it works fine, but when I change this fragment to any other fragment or close the app and then again run the app, the array list gets empty and nothing is shown.

I am not sure maybe there is something to do with savedInstanceState and SharedPreferences but don't know what to do exactly to solve this issue.

Here is my code for that fragment :

public class ShoppingListFragment extends Fragment {

    private ListView listView;
    EditText editText;
    ImageButton imageButton;
    CheckBox checkBox;
    private View view;

    ArrayList<String> list;
    ArrayAdapter adapter;

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

    public static ShoppingListFragment newInstance(String param1, String param2) {
        ShoppingListFragment fragment = new ShoppingListFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            //Restore the fragment's state here
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (view != null) {
            return view;
        }
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_shopping_list, container, false);

        editText = (EditText) view.findViewById(R.id.EtxtItem);
        imageButton = (ImageButton) view.findViewById(R.id.Imgbtnadd);
        checkBox = (CheckBox) view.findViewById(R.id.checkbox);

        listView = view.findViewById(R.id.ShoppingListView);


        list = new ArrayList<>();
        adapter = new ArrayAdapter<String>(getActivity(), R.layout.shopping_list_single_row, R.id.AddShoppingItem, list);
        listView.setAdapter(adapter);

        setHasOptionsMenu(true);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String item = editText.getText().toString();
                if (!item.isEmpty()) {
                    list.add(item);
                    adapter.notifyDataSetChanged();
                    editText.setText("");
                    Toast.makeText(getContext(), item + " added to Shopping List", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getContext(), "Please add an Item", Toast.LENGTH_LONG).show();
                }
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {

                final EditText UpdateList = new EditText(getActivity());
                UpdateList.setInputType(InputType.TYPE_CLASS_TEXT);
                UpdateList.setText(list.get(position));

                new AlertDialog.Builder(getActivity())
                        .setIcon(R.drawable.ic_list_foreground)
                        .setTitle(list.get(position))
                        .setPositiveButton("Update", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                new AlertDialog.Builder(getActivity())
                                        .setTitle("Update")
                                        .setView(UpdateList)
                                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                list.set(position, UpdateList.getText().toString());
                                                adapter.notifyDataSetChanged();
                                                Toast.makeText(getActivity(), "Updated", Toast.LENGTH_LONG).show();
                                            }
                                        })
                                        .setNegativeButton("Cancel", null)
                                        .show();
                            }
                        })
                        .setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                /* UPDATE THIS */
                                String val = adapterView.getItemAtPosition(position).toString();
                                list.remove(position);
                                adapter.notifyDataSetChanged();
                                Toast.makeText(getActivity(), "Deleted", Toast.LENGTH_LONG).show();
                            }
                        })
                        .setNeutralButton("Cancel", null)
                        .show();

                return true;
            }
        });
        return view;
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.delete, menu);
        MenuItem item = menu.findItem(R.id.SlistDeleteAll);
        item.getActionView();
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.SlistDeleteAll) {
            if (list.size() > 0) {
                list.clear();
                adapter.notifyDataSetChanged();
                Toast.makeText(getActivity(), "Shopping List Cleared", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getActivity(), "Shopping List Empty", Toast.LENGTH_LONG).show();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    int mCurCheckPosition = 0;

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //Save the fragment's state here
    }
}

I am new to Android app development. So, if anyone can help in regard to this, it will be great. Thanks in advance.

2 Answers

No need for shared preferences just initialize your array

  list = new ArrayList<>(); 

outside onCreateView() make it at the top of the class with list definition

ArrayList list= new ArrayList<>();

your array is empty becasue you are initializing array
list = new ArrayList<>(); adapter = new ArrayAdapter(getActivity(), R.layout.shopping_list_single_row, R.id.AddShoppingItem, list); listView.setAdapter(adapter);

...in onCreatView method if you want to store data and load as it before after reopening app then use shared preferences

Related