SciPhy
SciPhy

Reputation: 143

Initialize Strings[] in onCreate method

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!

Upvotes: 1

Views: 950

Answers (3)

user692168
user692168

Reputation:

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}.

Upvotes: 0

stinepike
stinepike

Reputation: 54672

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.

Upvotes: 2

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

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;
    }         
}

Upvotes: 4

Related Questions