0

I need some help with data management. Hopefully I can explain this well enough. I create and instantiate an ArrayList in Class A, but I want to display the data in Class B. It is a little trickier than this, let me explain my steps.

I created some setters and getters in Class A

public static void setArray(ArrayList<String> list) {
   ClassA.mList = list;
}

public static ArrayList<String> getArray() {
   return mList;
}

While in Class A, I populate my array with one item, mList.add("item"). Now that I have an item in my list (mList), I start a new Activity

Intent intent = new Intent(ClassA.this, ClassB.class);
startActivity(intent); 

I purposefully did not finish() this Activity. Now that I am in Class B, I test if the data persists by printing out the first item in the array using my getter method.

System.out.println("Data persists? " + ClassA.getArray().get(0));

Everything works fine up to this point. But now I finish() Class B, which brings me back to Class A. I added in onResume() for Class A to add another item to my list (mList) and thenI start the second Activity (Class B) again. I then use recursion to check if I have two items in my arraylist, and there is only 1. I also checked in onResume if I could print out anything, and the size of mList is 0. My guess is that it re-instantiated, and reset the list?

How can I maintain data in an ArrayList after leaving the Activity and then returning back? I want to be able to add/update data to that arraylist every time I return back to Class A

Thank you in advance

1 Answer 1

2

You should not use static methods to share non-static data between activities. For this purpose please use Intent you passing as temporary storage of your data. For example you provided you can refer to putStringArrayListExtra()

Sign up to request clarification or add additional context in comments.

1 Comment

Let me try this. Thanks for the suggestion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.