尝试在CustomSpinner中访问TextView时出现NullPointerException

时间:2016-04-19 21:41:31

标签: android android-layout nullpointerexception android-spinner android-custom-view

我正在尝试使用自定义微调器来查看日历视图。我已经编写了自己的自定义适配器。视图最初加载正常,但是当我尝试单击微调器下拉列表中的一个项目时,应用程序崩溃。

以下是我的活动代码:

public class CalendarEventsActivity  extends Activity {

protected ActivityHeader mHeader;
private Spinner mMonthDropdown;

@Override
protected void beforeMainContentCreated(Bundle savedInstanceState) {

}

public void onCreateMainContent(Bundle savedInstanceState) {
    super.onCreateMainContent(savedInstanceState);
    setRequestedOrientationByResourceID(R.integer.allow_landscape_calendar_events_activity);
    getWindow().setBackgroundDrawable(null);

    setContentView(R.layout.activity_calendar_events);

    mHeader = (ActivityHeader) findViewById(R.id.header);

    getSlidingMenu().setSlidingEnabled(false);

    setupMonthSpinner();
}

private void setupMonthSpinner() {
    mMonthDropdown = (Spinner) findViewById(R.id.month_spinner);
    String[] items = new String[] { "January", "February", "March",
            "April", "May", "June", "July", "August", "September",
            "October", "November", "December" };
    mMonthDropdown.setAdapter(new MyAdapter(this, R.layout.calendar_month_item, items));

    mMonthDropdown.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            System.out.println("you have now clicked......."+((TextView)parent.getChildAt(position)).getText().toString());

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub

        }
    });
}

public class MyAdapter extends ArrayAdapter<String> {

    String[] calendar_months;

    public MyAdapter(Context context, int textViewResourceId,
            String[] objects) {
        super(context, textViewResourceId, objects);
        this.calendar_months = objects;
    }

    @Override
    public View getDropDownView(int position, View convertView,
            ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView,
            ViewGroup parent) {

        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.calendar_month_item, parent, false);
        TextView label = (TextView) row.findViewById(R.id.calendar_month);
        label.setText(calendar_months[position]);

        return row;
    }
}
}

这是xml我在哪里定义Activity的活动布局(activity_calendar_events.xml):

<?xml version="1.0" encoding="utf-8"?>

<com.android.ui.ActivityHeader
    android:id="@+id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:gravity="center"
    app:actionButtonDrawable="@drawable/icon_add_member_inset"
    app:actionButtonDrawableHeight="35dp"
    app:actionButtonDrawableWidth="35dp"
    app:headerLabel="@string/calendar_events_header"
    app:menuButtonDrawable="@drawable/icon_navbar_back_inset"
    app:menuButtonDrawableHeight="35dp"
    app:menuButtonDrawableWidth="35dp"
    app:showMenuButton="true" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#F4F4F4"
    android:orientation="horizontal"
    android:layout_below="@+id/header" >

    <Spinner
        android:id="@+id/month_spinner"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="20dp"
        android:background="#F4F4F4"
        android:spinnerMode="dropdown"
        android:popupBackground="#F4F4F4"/>

    <TextView
        android:id="@+id/calendar_year"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:text="2016" />
</RelativeLayout>

这是xml我在哪里定义下拉列表各行的布局(calendar_month_item.xml):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.android.calendar"
android:id="@+id/calendar_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="8dp"
android:paddingLeft="15dp"
android:paddingTop="8dp"
android:textColor="#181512"
android:textSize="15sp"
android:textStyle="normal" />

最后是Logcat错误:

04-19 14:27:06.073: E/ThisLife(13008): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
04-19 14:27:06.073: E/ThisLife(13008):  at com.android.calendar.CalendarEventsActivity$1.onItemSelected(CalendarEventsActivity.java:78)
04-19 14:27:06.073: E/ThisLife(13008):  at android.widget.AdapterView.fireOnSelected(AdapterView.java:914)
04-19 14:27:06.073: E/ThisLife(13008):  at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:903)
04-19 14:27:06.073: E/ThisLife(13008):  at android.widget.AdapterView.access$300(AdapterView.java:48)
04-19 14:27:06.073: E/ThisLife(13008):  at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:873)
04-19 14:27:06.073: E/ThisLife(13008):  at android.os.Handler.handleCallback(Handler.java:739)
04-19 14:27:06.073: E/ThisLife(13008):  at android.os.Handler.dispatchMessage(Handler.java:95)
04-19 14:27:06.073: E/ThisLife(13008):  at android.os.Looper.loop(Looper.java:135)
04-19 14:27:06.073: E/ThisLife(13008):  at android.app.ActivityThread.main(ActivityThread.java:5343)
04-19 14:27:06.073: E/ThisLife(13008):  at java.lang.reflect.Method.invoke(Native Method)
04-19 14:27:06.073: E/ThisLife(13008):  at java.lang.reflect.Method.invoke(Method.java:372)
04-19 14:27:06.073: E/ThisLife(13008):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
04-19 14:27:06.073: E/ThisLife(13008):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

我相信这是编写自定义微调器的一种非常标准的方法。我尝试使用断点和特定行的所有数据点进行调试,导致NPE似乎不为空。我不确定这里发生了什么。任何建议都会有所帮助。

感谢。

3 个答案:

答案 0 :(得分:1)

更改行

class_getInstanceMethod

System.out.println("you have now clicked......."+((TextView)parent.getChildAt(position)).getText().toString());

请记住,根据您的适配器,每当请求视图时,getCustomView函数都会返回“膨胀”String selectedMonth = ((TextView) view.findViewById(R.id.calendar_month)).getText().toString(); System.out.println("you have now clicked......."+selectedMonth); 。然后,您在此视图上查找R.layout.calendar_month_item - 该视图应包含所选月份的值。请检查并确认是否有效。我希望如此。

答案 1 :(得分:0)

在设置适配器时,请尝试this,而不是传递CalendarEventsActivity.this。所以它看起来像:
mMonthDropdown.setAdapter(new MyAdapter(CalendarEventsActivity.this, R.layout.calendar_month_item, items));

答案 2 :(得分:-1)

TextView的id是calendar_year,而在您的代码中,您引用了calendar_month

Ctrl-d