gpt4 book ai didi

Android onItemSelected 空指针异常

转载 作者:行者123 更新时间:2023-11-29 16:06:57 25 4
gpt4 key购买 nike

即使我无法从我的测试中复制,我也相当一致地从我的 Android 应用程序的用户那里收到此错误消息。任何帮助是极大的赞赏。这是 logcat:

java.lang.NullPointerException
at com.janzen.bodybuildingdiet.MealOne$4.onItemSelected(MealOne.java:2172)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:882)
at android.widget.AdapterView.selectionChanged(AdapterView.java:865)
at android.widget.AdapterView.checkSelectionChanged(AdapterView.java:1017)
at android.widget.AdapterView.handleDataChanged(AdapterView.java:999)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:179)

这是代码 fragment (第 2172 行是“setTextColor(Color.WHITE);:

spinnerCarbs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
String selection = parentView.getItemAtPosition(
position).toString();

((TextView) spinnerCarbs.getChildAt(0))
.setTextColor(Color.WHITE);
((TextView) spinnerCarbs.getChildAt(0))
.setGravity(Gravity.CENTER);

carbsSelection = selection;
carbsSpinnerPosition = spinnerCarbs
.getSelectedItemPosition();
savePrefs("CARBS", carbsSpinnerPosition);
}

最佳答案

要么 spinnerCarbs 为空,要么它为空,因此它的第 0 个 child 为空。如果您想进行防御性编码,请执行

                if(spinnerCarbs != null && spinnerCarbs.getChildAt(0) != null){
((TextView) spinnerCarbs.getChildAt(0))
.setTextColor(Color.WHITE);
((TextView) spinnerCarbs.getChildAt(0))
.setGravity(Gravity.CENTER);
}

关于Android onItemSelected 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com