1

I'm trying to initialize an array of String[] depending of the value that comes from the previous activity. The compiler says there is an error in the following code and it says "Array constants can only be used in initializers". Is there no alternative to do what I'm trying to do?

public class ZeroParameter extends Activity{
int option, model;
String[] models;

protected void onCreate(Bundle savedInstanceState) 
{
    Bundle b = getIntent().getExtras();
    option = b.getInt("option");


    switch(option)
    {
        case 1:
        models={ "Mike" , "Charls" , "Jhon"}
        case 2:
        models={"Paul" , "Louis" };
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.zero_parameter);

    final Spinner spinModel=(Spinner)findViewById(R.id.spinnerModel0);
    spinModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            public void onItemSelected(AdapterView<?> arg0, View v, int position,long id) 
            {
                    model = spinModel.getSelectedItemPosition();
            }
            public void onNothingSelected(AdapterView<?> arg0) 
        { 
        }
    });

    ArrayAdapter<String> aa= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,models);
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinModel.setAdapter(aa);
}

}

Thanks you very much!!! I hope we can find a solution!

3 Answers 3

4

Change

switch(option)
{
    case 1:
    models={ "Mike" , "Charls" , "Jhon"};
    case 2:
    models={"Paul" , "Louis" };
}

to

switch(option)
{
    case 1: {
       models=new String[]{ "Mike" , "Charls" , "Jhon"};
       break;
    }
    case 2: {
       models=new String[]{"Paul" , "Louis" };
       break;
    }         
}
Sign up to request clarification or add additional context in comments.

1 Comment

You may need a break after case
2

use

case 1:
models= new String[] { "Mike" , "Charls" , "Jhon"}
break;
case 2:
models= new String[]{"Paul" , "Louis" };
break;

Reason

the error log says it all. You can only initialize array with constant value when declaring it.

models={"Paul" , "Louis" } 

is not an initializer

Another thing as Juned noticed. If you don't use break statement then for case 1 both statements will be done.

Comments

0

Use this instead:

case 1:
  models= new String[] { "Mike" , "Charls" , "Jhon"}
case 2:
  models= new String[]{"Paul" , "Louis" };

Java wants you to tell it what type the array will hold. It's just a security measure so that you cannot do something like {"A string", true}.

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.