1

I have an array adapter(string), and would like to convert it to a List<String>, but after a little googling and a few attempts, I am no closer to figuring out how to do this.

I have tried the following;

for(int i = 0; i < adapter./*what?*/; i++){
     //get each item and add it to the list
}

but this doesn't work because there appears to be no adapter.length or adapter.size() method or variable.

I then tried this type of for loop

for (String s: adapter){
    //add s to the list
}

but adapter can't be used in a foreach loop.

Then I did some googling for a method (in Arrays) that converts from an adapter to a list, but found nothing.

What is the best way to do this? Is it even possible?

jcw
  • 5,132
  • 7
  • 45
  • 54

2 Answers2

5
for(int i = 0; i < adapter.getCount(); i++){
     String str = (String)adapter.getItem(i);
}
M G
  • 1,240
  • 14
  • 26
  • 1
    That looks like exactly what I am looking for, thanks. I hate the fact that google can't make the length names uniform. Would it be too hard for them to have called the method `size()` or `length`? – jcw Sep 11 '13 at 18:06
  • 1
    Semantically, `getCount()` is more appropriated as it should inform about the number of views that the adapter will create, unlike the `ArrayList` or the array containing the data, which has indeed a size : the number of elements it contains. An `ArrayAdapter` doesn't necessarily contains data, so it has no size. – Mickäel A. Sep 11 '13 at 18:13
  • 1
    Also note that the **ArrayAdapter** class is generic, so if you did `new ArrayAdapter(...)` you can avoid casting the value returned by **getItem()**. – Mickäel A. Sep 11 '13 at 18:17
2

Try this

// Note to the clown who attempted to edit this code.
// this is an input parameter to this code.
ArrayAdapter blammo; 
List<String> kapow = new LinkedList<String>(); // ArrayList if you prefer.

for (int index = 0; index < blammo.getCount(); ++index)
{
    String value = (String)blammo.getItem(index);
    // Option 2: String value = (blammo.getItem(index)).toString();
    kapow.add(value);
}

// kapow is a List<String> that contains each element in the blammo ArrayAdapter.

Use option 2 if the elements of the ArrayAdapter are not Strings.

DwB
  • 37,124
  • 11
  • 56
  • 82