views:

48

answers:

3

Hello all,

I having a pretty slow day tday so bare with me. Basically I have an android context menu with various selections and depending on the user selection I want to start an intent. The intent starts the same activity for all the buttons but will contain different String variables depending on the selection. I am currently using a switch, case methodology for my click listener but keep running into 'duplicate local variable' problems as I try to eliminate code repetition! If anyone could provide a-bit of pseudo-code that would be even better!

Cheers

+1  A: 

It's hard to tell without seeing some code, but "duplicate local variables" together with "switch case" makes me think you're declaring a variable in one of the cases with the same name as a variable from another case.

Code within different cases of the same switch is all in the same scope, unless you surround the code within a case with brackets, like this:

switch(VALUE) {
case A: {
    String string = "";
}
case B: {
    //Same variable name, possible since it's in a different scope now.
    String string = "";
}
}

So either use brackets, or simply make sure you're using different variable names across the cases.

benvd
+1  A: 

Hi Ally,

you can use intent.putExtra(String name, String value) and push it to the other activity.

Pseudo code:

Button1.value = "X" ;
Button2.value = "Y" ;

onClickListner(View v) {
Intent intent = new Intent() ;
intent.putExtra("ButtonValue", v.value() ) ;
// extra code goes here...
}

Hope this is what you were looking for..

VInay

Vinay
A: 

I like to use set/getTag(Object), as you can put any type you like into it (as long as you're careful about getting it out again):

button1.setTag(MyClass.STATIC_INT_1);
button2.setTag(MyClass.STATIC_INT_2);
button1.setOnClickListener(Click);
button2.setOnClickListener(Click);


private OnClickListener Click(View v) {
Intent intent = new Intent() ;
intent.putExtra("Value", Integer.parseInt(v.getTag().toString()) ) ;
···
}
fredley