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?

1

2 Answers 2

5
for(int i = 0; i < adapter.getCount(); i++){
     String str = (String)adapter.getItem(i);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
Also note that the ArrayAdapter class is generic, so if you did new ArrayAdapter(...)<String> you can avoid casting the value returned by getItem().
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.