1

即使我无法从我的测试中复制,我也相当一致地从我的 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)

这是代码片段(第 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);
                }
4

2 回答 2

4

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

                if(spinnerCarbs != null && spinnerCarbs.getChildAt(0) != null){
                    ((TextView) spinnerCarbs.getChildAt(0))
                            .setTextColor(Color.WHITE);
                    ((TextView) spinnerCarbs.getChildAt(0))
                            .setGravity(Gravity.CENTER);
                }
于 2013-07-01T17:16:08.727 回答
0

你可以试试

if(spinnerCarbs == null) return;

然后你们剩下的代码

于 2013-07-01T17:31:42.323 回答