Android:微调器上的getSelectedItem问题 [英] Android: problems with getSelectedItem on a spinner
问题描述
我有一个Spinner
,并将选定的项目放在邮件正文中.
这是我的代码:
I have a Spinner
, and put the selected item in the body of a mail.
this is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modulo);
Spinner spinnerTaglia = (Spinner) findViewById(R.id.spinnerTaglia);
// Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Taglie, 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);
spinnerTaglia.setPrompt("Seleziona la taglia!");
// Apply the adapter to the spinner
spinnerTaglia.setAdapter(new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
// R.layout.contact_spinner_nothing_selected_dropdown, // Optional
this));
final String taglia = spinnerTaglia.getSelectedItem().toString();
Button btnCompilaOrdine = (Button) findViewById(R.id.btnCompilaOrdine);
btnCompilaOrdine.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MAIL@gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "MAIL OBJECT");
i.putExtra(Intent.EXTRA_TEXT , "Taglia: "+taglia);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Modulo.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
应用程序在模拟器中正确启动,调试器什么也没有显示(我正在使用Android Studio),但是当我单击该按钮后,该应用程序崩溃了,Android Studio的调试器显示了
The application start correctly in the emulator and the debugger show me nothing (I'm using Android Studio) but when i click on the button that take me in this activity the application crash and the Android Studio's Debugger show me a java.lang.NullPointerException
in the row:
最终字符串标签= spinnerTaglia.getSelectedItem().toString();
final String taglia = spinnerTaglia.getSelectedItem().toString();
我该如何解决?
推荐答案
getSelectedItem()
如果在微调器上没有选择任何内容,并且调用toString()
使应用程序崩溃,则返回null.摆脱
getSelectedItem()
returns null if there is nothing selected on your spinner and calling toString()
is making your application crash. Get rid of
final String taglia = spinnerTaglia.getSelectedItem().toString();
,然后在您的onClick中完成
and in your onClick do:
if (spinnerTaglia.getSelectedItem() == null) {
return;
}
String taglia = spinnerTaglia.getSelectedItem().toString();
// the other code
这篇关于Android:微调器上的getSelectedItem问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!