Reputation: 35
how do i pass char1 out of the onCreate method into another method -- in this case, pass it into selectChar2? Can i make char1 and char2 global or something? I'm not sure what's the proper way to go about this. please help!
private String char1,char2; // does this even do anything? I thought this would let me use char1 and char2 anywhere.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_char2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String char1 = (String) extras.getString("char1"); //is the (String) necessary?
TextView textView = (TextView) findViewById(R.id.header);
textView.setText(char1+" vs "+"char2");
}
}
public void selectChar2(View v) {
Button btn = (Button)v;
String char2 = btn.getText().toString();
Intent intent = new Intent(PickChar2.this, DisplayMatchUp.class);
Bundle extras = new Bundle();
extras.putString("Character1",char1); //char1 here is null...how do I get the value from the method above?
extras.putString("Character2", char2);
intent.putExtras(extras);
startActivity(intent);
Upvotes: 0
Views: 11260
Reputation: 7822
You already declared the variables as global, but later you declared a local variable with the same name. The local variable will be used instead. To ensure that the global variable is used instead, use "this" keyword.
this.char2
refers to the global variable char2
char2
refers to the local variable char2
Upvotes: 1
Reputation: 195
You should probably make it public, or make it a parameter in both methods.
Upvotes: 0
Reputation: 8764
At the top of your program, you are creating a global variable char1
...
private String char1,char2;
But in the onCreate()
method, you have the following line...
String char1 = (String) extras.getString("char1");
The word String at the beginning of the line is creating a Local variable called char1
which is separate to the global variable char1
which you're creating at the top of your program.
You need to remove the String
to simply be this...
char1 = (String) extras.getString("char1");
By doing this, you will now be assigning the value to the global variable at the top of your program, and can thus use it anywhere in this class that you wish.
Upvotes: 0
Reputation: 22637
as it is, you have declared and used two separate variables:
1 is scoped to the class instance (it's accessible in any non-static scope within the class). 2 is scoped in the block where it is defined. in this case, simply don't create a local variable, and use the instance variable,
char1 = (String) extras.getString("char1");
Upvotes: 2