Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add items to a stringArray in an arrayList programmatically?

Tags:

arrays

android

This is my array.xml file in the res/values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="updateInterval">
           <item name="1000">Pico TTS</item>
          <item name="5000">Invox TTs</item>
    </string-array>
</resources>

I need to add some more items to the updateInterval array list. How can I add the items that are dynamically coming from server programmatically?

like image 688
bharath gangupalli Avatar asked Jan 10 '12 06:01

bharath gangupalli


People also ask

How do you add elements to a String array?

By using ArrayList as intermediate storage:Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.

How do you add items to a String array in Java?

You can also add an element to String array by using ArrayList as an intermediate data structure. An example is shown below. As shown in the above program, the string array is first converted into an ArrayList using the asList method. Then the new element is added to the ArrayList using the add method.


1 Answers

You can't add item directly to that string array.

But you can use that array and dynamically add elements to that string array.

Do in this way.

    String[] array = getResources().getStringArray(R.array.updateInterval);
    System.out.println("--array.length--"+array.length);
    List<String> list = new ArrayList<String>();
    list = Arrays.asList(array);
    ArrayList<String> arrayList = new ArrayList<String>(list);
    arrayList.add("TTS");
    array = arrayList.toArray(new String[list.size()]);
    System.out.println("--array.length--"+array.length);
like image 73
Debarati Avatar answered Oct 09 '22 12:10

Debarati