我正在尝试将Spinner数组中选择的值项传递给API调用请求。
我无法将值传递到setOnItemSelectedListener之外(新的AdapterView.OnItemSelectedListener()。
我试图使用Stack溢出答案中提供的大多数选项,但是当我尝试打印String时,它显示为null。
将字符串变量放在外面的正确方法是什么,以便我可以通过请求将其作为值发送,甚至打印出来。
public class Profile2 extends AppCompatActivity implements View.OnClickListener {
private String gender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//final String gender = (String) genderspinner.getSelectedItem().toString().trim();
// Spinner gender = (Spinner) findViewById(R.id.genderspinner);
//final EditText etGender = (EditText) findViewById(R.id.etGender);
final Spinner genderspinner = findViewById(R.id.genderspinner);
//String gender;
ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this,R.array.gender, R.layout.support_simple_spinner_dropdown_item);
arrayAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
genderspinner.setAdapter(arrayAdapter);
genderspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String gendervalue = parent.getItemAtPosition(position).toString();
// Object item = parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final String gender = String.valueOf(genderspinner.getSelectedItem());
Log.i("TAG", "gender here : "+gender);
// when I run the log, it is always empty.
//final String gender = String.valueOf(genderspinner.getSelectedItem());
// genderspinner.setOnItemSelectedListener(this);
updateprofile(gender)
});
}
private void updateprofile(gender) {
// API call which sends the gender data
}
}
答案 0 :(得分:1)
声明global variable
以存储spinner's selected value
。请尝试以下代码。
String gendervalue="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//final String gender = (String) genderspinner.getSelectedItem().toString().trim();
// Spinner gender = (Spinner) findViewById(R.id.genderspinner);
//final EditText etGender = (EditText) findViewById(R.id.etGender);
final Spinner genderspinner = findViewById(R.id.genderspinner);
//String gender;
ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this,R.array.gender, R.layout.support_simple_spinner_dropdown_item);
arrayAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
genderspinner.setAdapter(arrayAdapter);
genderspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
gendervalue = parent.getItemAtPosition(position).toString();
// Object item = parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Log.i("TAG", "gender here : "+gendervalue);
updateprofile(gendervalue)
});
}
您现在可以查看日志,它会显示所选的值。
答案 1 :(得分:1)
创建全局变量并在该变量中设置值并访问所需的位置。