Search code examples
androidarraylistadditionlogcat

Error: add item to ArrayList


Method of add gives error for ArrayList. It isn't adding.

    public List<String> arrayList;

...

arrayList = new ArrayList<String>();

...

savenumberButton.setOnClickListener(new View.OnClickListener()
    {

        public void onClick(View v)
        {
            String str = numberText.getText().toString();
            Integer cout = listView.getCount()+ 1;
            String str1 = cout.toString().concat("."+str);

            try {
                arrayList.add(listView.getCount(), str1);
            } catch (Exception e) {
                Log.w("Error", "arraylist.add is not running!");
            }

            arrayAdapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
            blockNumberText.setText(" ");
        }
    });

...

Solution

  • Now that you have posted the exception and line number and more details in the comments, this seems be because when you call asList() This method "Returns a fixed-size list backed by the specified array.." then you just cast it to an ArrayListwhich is incorrect.

    so the method add throws the UnsupportedOperationException because the List has a fixed size and cannot be modified.

    instead try

    arrayList = new ArrayList<String> (Arrays.asList(TextUtils.split(number, ",")));