Ok so I am working on an android app and I have implanted spinners… I have a total of four spinners and I have learned that if the spinner reads the options from the strings it has a defined number for the selection(i.e the first option is “0” next is “1” and so on)
I have the following code for the spinner
Spinner a = (Spinner) findViewById(R.id.spinner1);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView adapter, View v, int a,
long lng) {
// do something here
Toast.makeText(adapter.getContext(), "You selected: " + a,
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView arg0) {
// do something else
}
});
and another one but with the int “b”
but later on in the same class I want to use some maths to get e=a,b (i.e if a=6 and b=5 e=65, or a=4 and b=3 e=43)
This is easily done by executing
int e=a*10+b;
The problem is I want to display this when you press a button, so I have the following code
public void Calc(View v) {
int e = a * 10 + b;
Toast.makeText(this, "Value: " + e, Toast.LENGTH_LONG).show();
}
but results in the error “”a” & “b” cannot be resolved to a variable”
why is this and how can I create a button that will be able to read these variables?
It’s a matter of scope, since you declared
ain a method, it is not accesible outside of the method. Declare the spinner as class members, and only assign it in the method:class scope:
In the method:
Then: