1

This my might be a stupid question, but how do you work with String Array?

I am trying to do something like this, but my app would crash upon launching.

String names [] = null ; 

    names[0]= "I am";
    names[1]= "Ammar";

    Toast.makeText(getApplicationContext(), names[1] , Toast.LENGTH_SHORT).show(); 
3
  • 1
    can you post logcat ? Commented Feb 26, 2013 at 6:41
  • You must be getting NullPointerException Commented Feb 26, 2013 at 6:45
  • you need to define string length before start working with it you are getting null pointer exception or Either Array out of bound Exception becasue your array size is zero and you are trying to access the 0+nth index that is not defined in Array so causing your app to get Crash Commented Feb 26, 2013 at 6:49

7 Answers 7

2

You have to create the array, just like any other array

String names[] = new String[size];
Sign up to request clarification or add additional context in comments.

Comments

1

you should define array size.

String name[] = new String[2];

Comments

1

You can use :

String[] names = new String[2];

names[0] = "I am";
names[1]= "Ammar";

    Toast.makeText(getApplicationContext(), names[1] , Toast.LENGTH_SHORT).show();

may be you are getting error because you have not allocated memory to string array. You have assigned null to the array that's why the application is crashing.

Comments

1
String[] names = { "I am", "Ammar" }; 

Comments

1

Array follows the concept of static allocation of memory so you must define how much memory or size you need before using it.

String[] names = new String[10];

Comments

0

Try replacing

String names [] = null ;

with

String names[] = new String[2]; 

Comments

0

This is a standard issue with Object Instantiation. If you're going to define a reference, you must either point it to an already existing object OR create a new reference to the object using the new keyword.

Ex:

[Class] x = new [Class]()

Where [Class] is the object you're wanting to instantiate/use.

Whenever an object reference is created and is not instantiated, that object will be initialized to null.

Ex:

[Class] x;

after this line, x will be null since it does not have a valid object reference (new or not).

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.