-1

My goal is to create an ArrayList that can be accessed from any activity in the application, so I created a class with static ArrayList<>:

public class CategoryArrayList {
    public static String id;
    public static List<String> category_spinner_user = new ArrayList<>();

public static void addCategory_spinner_user(String stringToBeAdded) {
        CategoryArrayList.category_spinner_user.add(stringToBeAdded);
    }

and then try to add an item to it by a call through an Activity:

public class TestActivity extends AppCompatActivity {
        Button button;
        public void testClicked(View view){
            CategoryArrayList.category_spinner_user.add("AAA");
        }  
}

ฺBut it resulted in an FATAL_EXCEPTION error:

java.lang.IllegalStateException: Could not execute method for android:onClick

Caused by: java.lang.reflect.InvocationTargetException

Caused by: java.lang.UnsupportedOperationException

Catching exception resulted in the same error report:

W/System.err: java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148)

Changing ArrayList<> to LinkedList<> (as suggested in Why do I get an UnsupportedOperationException when trying to remove an element from a List?) does not help either.

How to fix this?

Community
  • 1
  • 1
Nocab_Evol_1
  • 41
  • 1
  • 2
  • 9

2 Answers2

2

Try code below for layout and attention that define function name of android:onClick the same function name testClicked(View view) in TestActivity

<Button
    android:onClick="testClicked"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="add"/>
nhonnq
  • 184
  • 1
  • 9
1

Recommend to use safe solution for view click with click listener:

View(your button).setOnClickListener(... ...);

Some brand devices could crash for using 'android:onClick= ...' in view layout.

Xcihnegn
  • 11,579
  • 10
  • 33
  • 33