0

I want to have a global ArrayList variable in my android application and I was just wondering how to save this list of Fragments when the app is finished and to get that same ArrayList back when the app restarts?

Lucas N
  • 69
  • 9

2 Answers2

1

Give an id to each Fragment and save the list of ids to SharedPreferences. When you restart app, inflate/display Fragments in the order of their ids that you saved to SharedPreferences.

How to write/read ArrayList to/from SharedPreferences: https://stackoverflow.com/a/22985657/5250273

Community
  • 1
  • 1
Ugurcan Yildirim
  • 5,973
  • 3
  • 42
  • 73
0

You should just store the arraylist before your application is killed by android. And when your application is starting, your application should load the data.

Let me explain more. Before this implementation, I think you should check the fragment's lifecycle.

onSaveInstaceState() method is called before onPause() (before fragment is killing). So you should save your data in this method.

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // Storing my arraylist on bundle
    outState.putStringArrayList("savedList", list);
}

To load your data, actually there is a OnRestoreInstanceState() method that is called after onCreate() ( before creating a new activity ) for activity. However there is no OnRestoreInstanceState() lifecycle method for fragments. So you can use onCreate(), onCreateView() or onActivityCreated() methods to load your date.

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
          setContentView(R.layout.activity_main);
          if(savedInstanceState != null){
            // Loading my arraylist
            list=savedInstanceState.getStringArrayList("savedList");
          } 

There are many options about storing data on android.

  • Saving key-value pairs of simple data types in a shared preferences file
  • Saving arbitrary files in Android's file system
  • Using databases managed by SQLite

You should just make up your mind to choose your way to save your date.

I hope its help you.

ziLk
  • 3,120
  • 21
  • 45