【发布时间】:2020-06-16 18:48:09
【问题描述】:
我正在使用多个 StringArrary,我可以在相应的 StringArray 中打印 Toast 消息,但不幸的是,我遇到了在块外显示 toast 的问题。我在下面分享我的代码
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) {
}
我的变量是这样的
String[] upz_code;
String[] union_code;
我的数组是这样的
private String[] Union = {"A", "B",};
private String[] Union = {"C", "D",};
我得到的错误是:
java.lang.NullPointerException: Attempt to read from null array
此错误导致应用程序崩溃并且不了解其中的缺陷。我该如何克服这个或我做错了什么?
【问题讨论】:
-
请发布完整的代码块。当您尝试在
Toast中使用它时,您可能正在尝试访问超出范围的变量 -
请显示更多代码,也许是发生这种逻辑的整个函数。从您显示的 sn-p 中不清楚 - 它似乎不是从函数的开头开始。
-
您好,我更新代码(全功能)。希望你现在能理解。
-
还没有@ArvindKumarAvinash
标签: java android arrays nullpointerexception