• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Arrays - help needed..

tlw

Lurker
Hello, please explain me why the below is causing NullPointerException:

...
String[] some_array;

@Override
public void onCreate(Bundle savedInstanceState) {
...
some_array[0] = "something";
...
}
...

What is the correct way to work with this array?

Thank You.
 
The array has to be initialized before it can store elements. So before you do
Code:
some_array[0] = "something";
you have to call
Code:
some_array = new String[12]
Change the number 12 in the brackets to the number of elements you want the array to be able to store. If it's 12, you can store 12 elements, and the last index is 11.
 
Thank You, but what if I don't know how much elements will be in the array?
Also, what is the first line for? I thought it is initializing too...

String[] some_array;
 
Your line:

"String[] some_array;"

Only declares the variable "some_array" as a StringArray which has the value "null".
Adding the "= new..." initiates it and actually creates a new StringArray object to which you can then assign Strings. Unfortunately you always have to give the max length of the array when initializing it :-/

Alternately your could use and ArrayList of Strings, which will give some more flexibility regarding length etc.
 
You can also do something like this:

Code:
String[] myStringArray = {"apples","oranges","grapes"};


Also I agree with JamTheMan, in that an ArrayList is MUCH more flexible. "Primative" arrays are a bit unruly.

.
 
Back
Top Bottom