Android, how to populate a CharSequence array dynamically (not initializing?)

37,193

Solution 1

Use a List object to manage items and when you have all the elements then convert to a CharSequence. Something like this:

List<String> listItems = new ArrayList<String>();

listItems.add("Item1");
listItems.add("Item2");
listItems.add("Item3");

final CharSequence[] charSequenceItems = listItems.toArray(new CharSequence[listItems.size()]);

Solution 2

You are almost there. You need to allocate space for the entries, which is automatically done for you in the initializing case above.

CharSequence cs[];

cs = new String[2];

cs[0] = "foo"; 
cs[1] = "bar"; 

Actually CharSequence is an Interface and can thus not directly be created, but String as one of its implementations can.

Solution 3

You can also use List, to have a dynamic number of members in the array(list :)):

List<CharSequence>  cs = new ArrayList<CharSequence>();

cs.add("foo"); 
cs.add("bar"); 

If you want to use array, you can do:

CharSequence cs[];

cs = new String[2];

cs[0] = "foo"; 
cs[1] = "bar"; 
Share:
37,193

Related videos on Youtube

MarcoS
Author by

MarcoS

I'm a sailor. I love roaming in the Mediterranean sea on any wood piece you can stick a mast and a sail on. In my spare time I do software engineering in Turin, as a full-stack developer. I start my coding ages ago with x86 assembly; then I go with C, bash, Perl, Java; Android; currently I do MEAN stack: MongoDB, Express.js, Angular.js and of course Node.js. Obviously on the shoulders of the GNU/Linux O.S..

Updated on March 11, 2020

Comments

  • MarcoS
    MarcoS over 4 years

    How do I change something like this:

    CharSequence cs[] = { "foo", "bar" };
    

    to:

    CharSequence cs[];
    
    cs.add("foo"); // this is wrong...
    cs.add("bar"); // this is wrong...
    
  • MByD
    MByD almost 13 years
    This won't compile, Arrays don't have add method.
  • MarcoS
    MarcoS almost 13 years
    Sorry, but, on "cs.add(...)", I get: "Cannot invoke add(String) on the array type CharSequence[]"...
  • Jehy
    Jehy over 11 years
    should be listItems.add("Item1");