Java android中在Toast消息中打印StringArray[]时出现NullPointerException
我正在使用一些多StringArray,我可以在相应的StringArray中打印Toast消息,但不幸的是,我在块外显示Toast时遇到了一个问题。我在下面分享我的代码Java android中在Toast消息中打印StringArray[]时出现NullPointerException,java,android,arrays,nullpointerexception,Java,Android,Arrays,Nullpointerexception,我正在使用一些多StringArray,我可以在相应的StringArray中打印Toast消息,但不幸的是,我在块外显示Toast时遇到了一个问题。我在下面分享我的代码 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent.getId() == R.id.region) { positions = spinner_re
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.region) {
positions = spinner_region.getSelectedItemPosition();
region_code = this.getResources().getStringArray(R.array.region_code);
//Toast.makeText(this, region_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.district) {
positions = spinner_district.getSelectedItemPosition();
district_code = this.getResources().getStringArray(R.array.district_code);
//Toast.makeText(this, district_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.upz) {
positions = spinner_upz.getSelectedItemPosition();
upz_code = this.getResources().getStringArray(R.array.upz_code);
//Toast.makeText(this, upz_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.union) {
positions = spinner_union.getSelectedItemPosition();
union_code = this.getResources().getStringArray(R.array.upz_code);
//Toast.makeText(this, union_code[positions], Toast.LENGTH_SHORT).show();
}
if (parent.getId() == R.id.village) {
positions = spinner_village.getSelectedItemPosition();
vill_code = this.getResources().getStringArray(R.array.village_code);
//Toast.makeText(this, vill_code[positions], Toast.LENGTH_LONG).show();
}
// Showing toast message here gives the error
//but in individual codeblock this show perfectly
Toast.makeText(this, union_code[positions]+upz_code[positions], Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
我的数组就像
private String[] Union = {"A", "B",};
private String[] Union = {"C", "D",};
我得到的错误是:
java.lang.NullPointerException: Attempt to read from null array
此错误导致应用程序崩溃,无法理解缺陷。我怎样才能克服这个问题或我做错了什么?试试这个
if(union_code!=null){
Toast.makeText(this,union_code[positions].toString() +upz_code[position].toString(),Toast.LENGTH_SHORT).show();
}
如果您只想在空的情况下显示toast,可以使用if(union\u code!=null)
。或者,如果您想在任何情况下展示祝酒辞,您可以使用此款:
Toast.makeText(this,
"" + union_code[positions].toString() + upz_code[position].toString(),
Toast.LENGTH_SHORT).show();
我认为,它应该可以工作。请发布完整的代码块。在
Toast
中使用变量时,您可能试图访问超出范围的变量。请显示更多代码,可能是发生此逻辑的整个函数。从您显示的代码片段中看不清楚-它似乎不是从函数的开头开始的。您好,我更新了代码(完整函数)。希望你现在能理解。还没有@ArvindKumarAvinash
Toast.makeText(this,
"" + union_code[positions].toString() + upz_code[position].toString(),
Toast.LENGTH_SHORT).show();