Android: Specify array size?

14,323

Solution 1

if you want dynamic size then use arraylist. something like:

public ArrayList<String> myList = new ArrayList<String>();

...

myList.add("blah");

...

for(int i = 0, l = myList.size(); i < l; i++) {
  // do stuff with array items
  Log.d("myapp", "item: " + myList.get(i));
}

Solution 2

You should write it like this.

String[] videoNames = new String[5]; // create videoNames array with length = 5
for(int i=0;i<videoNames.length();i++)
{
   // IMPORTANT : for each videoName, instantiate as new String.
   videoNames[i] = new String(""); 
}

Solution 3

Use as:

public String[] videoNames = new String[SIZE]; // SIZE is an integer

or use ArrayList for resizable array implementation.


EDIT: and initialize it like this:

int len = videoNames.length();
for(int idx = 0; idx < len; idx++) {
   videoNames[idx] = ""; 
}

With ArrayList:

ArrayList<String> videoNames = new ArrayList<String>();
// and insert 
videoNames.add("my video");

Solution 4

Use ArrayList if you want to add elements dynamically. Array is static in nature.

How to add elements to array list

Thanks Deepak

Solution 5

If you want to use an arraylist as written in your commnet here is an arraylist

ArrayList<String> videoNames =new ArrayList<String>();

add as many as you want no need to give size

    videoNames.add("yourstring");
videoNames.add("yourstring");
videoNames.add("yourstring");
videoNames.add("yourstring");

to empty the list

 videoNames.clear();

to get a string use

String a=videoNames.get(2);

2 is your string index

Share:
14,323
Kris
Author by

Kris

I love programming.

Updated on June 14, 2022

Comments

  • Kris
    Kris almost 2 years

    anyone knows how to specify array size?

    public String[] videoNames = {""}
    

    the array above can accomodate only one value. i want to extend how many values this array can accomodate.