Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android case statement help

I'm trying to make my case statement open up a different class depending on what button is pressed. I got this working fine for one button but am unsure how to proceed for two buttons.

Heres my code so far:

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
        break;
    case R.id.reminderList_button:
        Intent i = new Intent (this, ReminderListActivity.class);
        startActivity(i);
        break;

    }

}

This gives an error because I'm reusing the local variable (i) - if anyone could let me know how to do this properly it would be much appreciated.

like image 229
user319940 Avatar asked Oct 13 '22 19:10

user319940


1 Answers

You could declare the variable i before the switch statement. This is especially preferable to "scoping" if you plan to use the variable i after the switch statement:

public void onClick(View v) {
    Intent i = null;
    switch (v.getId()) {
    case R.id.about_button:
        i = new Intent(this, About.class);
        break;
    case R.id.reminderList_button:
        i = new Intent (this, ReminderListActivity.class);
        break;
    }
    startActivity(i);
    ...; // other statements using `i'
}
like image 186
Victor Zamanian Avatar answered Oct 18 '22 03:10

Victor Zamanian