i read many similar questions on this thread, but none of them help me... This is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.imc_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.imc_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. You can retrieve the selected item using
imc_met = parent.getItemAtPosition(pos).toString();
}
I declare imc_met as public String imc_met;
. The problem is that imc_met does not contain the value of the selected item of the spinner, but it's null...
Where's the problem?
Thx in advance.
getItemAtPosition(i).
Android Dependency Injection using Dagger with Kotlin This example demonstrates how to get Spinner value in Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Let the Spinner's first value be something like "-please select-". when the user clicks on the next button perform validation and check whether the value of the selectedItem in the spinner is "-please select-" and if yes, then display a toast and ask the the user to select something from the spinner.
Use:
imc_met=Spinner.getSelectedItem().toString();
Instead:
imc_met = parent.getItemAtPosition(pos).toString();
Updated:
Seem you assigning Listener to your spinner not in correct way, do something like below:
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String imc_met=spin.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Try this:
imc_met=Spinner.getSelectedItem().toString();
I'm sorry. I forgot
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
imc_met=Spinner.getSelectedItem().toString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With