In my android application I want to be able to add a string value to a static arraylist I have declared on my main android activity. The logic goes like this:
1) When you click a button and an activity starts. On the oncreate method I want to save the name of the class that is the current activity to a string value. For example:
String className = "com.lunchlist.demo";
After this value is assigned I want to immediately add this string value to a Static ArrayList I have declared in my main android activity (meaning first android activity that starts) After adding the value
I did something like this:
static String List<String> members = new ArrayList<String>();
This is declared in my main activity. Now when I click a button to start another activity I use this to add the string classname for that current activity to my arraylist in my oncreate method:
String className = "com.lunchlist.demo"
members.add(className);
My question is now, would this add the string value to my arraylist and save it for later use? For example If I click three different buttons this will add three different className values to the arraylist. Would this then store a string value that would hold three different string values for my members arraylist? How would I check each item in my arraylist to see if the values are being added when a new activity is started?
I’m asking this because I will need to retrieve this and store these values using shared preferences and later retrieve them and starting an intent using the string value which is the class to start the activity. I got the activity to start with a string value of a class name I’m just having trouble storing them.
Answering to all of your questions:
Yes. Your code seems perfect to do it with no problems.
If you tell to your button’s
onClickListenerto add a string to the members ArrayList then it will be done and no matter if you already had previously added that member to the ArrayList because array lists don’t care if there is duplicated data or not.You have to iterate your array list with a for or a for-each cicle and then print that member name as a log entry.
For-each cicle
Simple For cicle
If you try to print/ log a value which index is out of range, i.e.,
i < 0 || i >= listSizethen a IndexOutOfBoundsException will be thrown and crash your app.