首页 文章

自定义控件中的recyclerview和gridview空指针异常

提问于
浏览
1

我按照this tutorial并应用了一些更改并在 recyclerview 中获得了 nullPointerException .

我在 gridview 也遇到了这个错误

我初始化 recyclerview 这段代码有什么问题?

custom_calendar_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">

<!-- date toolbar -->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="12dp"
    android:paddingBottom="12dp"
    android:paddingLeft="30dp"
    android:paddingRight="30dp">

    <!-- prev button -->
</RelativeLayout>

<!-- days header -->
<LinearLayout
    android:id="@+id/calendar_header"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:gravity="center_vertical"
    android:orientation="horizontal">
</LinearLayout>

<!-- days view -->
<android.support.v7.widget.RecyclerView
    android:id="@+id/calendarRecycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.v7.widget.RecyclerView>

customCalendarView.java

public class customCalendarView extends LinearLayout {

    // how many days to show, defaults to six weeks, 42 days
    private static final int DAYS_COUNT = 42;

    // current displayed month
    private Calendar currentDate = Calendar.getInstance();

    // internal components
    private LinearLayout header;
    private ImageView btnPrev;
    private ImageView btnNext;
    private TextView txtDate;
    private RecyclerView grid;

    public customCalendarView(Context context) {
        super(context);
        initControl(context);
    }

    public customCalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public customCalendarView(Context context, AttributeSet attrs, int     defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void initControl(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.custom_calendar_view, this);
        //assignClickHandlers();
        updateCalendar();
    }

    private void assignUiElements() {
        // layout is inflated, assign local variables to components
        header = (LinearLayout) findViewById(R.id.calendar_header);
        btnPrev = (ImageView) findViewById(R.id.calendar_prev_button);
        btnNext = (ImageView) findViewById(R.id.calendar_next_button);
        txtDate = (TextView) findViewById(R.id.calendar_date_display);
        grid = (RecyclerView) findViewById(R.id.calendarRecycler);
    }

    public void updateCalendar() {
        assignUiElements();

        List<calendarInf> cells = new ArrayList<>();
        Calendar calendar = (Calendar) currentDate.clone();

        // determine the cell for current month's beginning
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int monthBeginningCell = calendar.get(Calendar.DAY_OF_WEEK) - 1;

        // move calendar backwards to the beginning of the week
        calendar.add(Calendar.DAY_OF_MONTH, -monthBeginningCell);

        // fill cells
        while (cells.size() < DAYS_COUNT) {
            calendarInf ci = new calendarInf();
            ci.date1 = calendar.getTime().toString();
            ci.date2 = "2";
            ci.date3 = "3";
            cells.add(ci);
            //Log.d("cells", "updateCalendar: "+cells.);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        CustomCalendarAdapter adapter = new   CustomCalendarAdapter(getContext(), cells);
        RecyclerView.LayoutManager mLayoutManager=new GridLayoutManager(getContext(),2);
        grid.setLayoutManager(mLayoutManager);

        grid.setAdapter(adapter);
    }
}

CostumCalendarAdapter.java

public class CustomCalendarAdapter extends   RecyclerView.Adapter<CustomCalendarAdapter.calendarViewHolder >{

    private LayoutInflater inflater;
    List<calendarInf> data = Collections.emptyList();
    Context context;

    public CustomCalendarAdapter(Context context,List<calendarInf> data)
    {
        inflater = LayoutInflater.from(context);
        this.data = data;
        this.context=context;
    }



    @Override
    public CustomCalendarAdapter.calendarViewHolder         onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.calendar_grid,parent,false);
        calendarViewHolder holder=new calendarViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(CustomCalendarAdapter.calendarViewHolder   holder, int position) {
        calendarInf current=data.get(position);
        holder.txtDate1.setText(current.date1);
        holder.txtDate2.setText(current.date2);
        holder.txtDate3.setText(current.date3);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class calendarViewHolder extends RecyclerView.ViewHolder{
        TextView txtDate1;
        TextView txtDate2;
        TextView txtDate3;

        public calendarViewHolder(View itemView) {
            super(itemView);
            txtDate1= (TextView) itemView.findViewById(R.id.txtDate1);
            txtDate2= (TextView) itemView.findViewById(R.id.txtDate2);
            txtDate3= (TextView) itemView.findViewById(R.id.txtDate3);


        }
    }
}

CalendarActivity.java

public class CalendarActivity extends BaseActivity {
    //FragmentManager manager;
    private BottomSheetBehavior mBottomSheetBehavior;
    TextView txtHello;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);




    View bottomSheetView = findViewById(R.id.bottom_sheet);
        mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheetView);
                 mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);


        customCalendarView cv = ((customCalendarView)findViewById(R.id.calendar_view));
        cv.updateCalendar();


    }
}

activity_calendar.xml

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.aysha.todocln.CalendarActivity"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/activity_calendar"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.aysha.todocln.customCalendarView
    android:id="@+id/calendar_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
 </RelativeLayout>
<!-- bottom sheet layout -->
 <RelativeLayout
    android:id="@+id/bottom_sheet"
    android:background="@color/colorAccent"
    android:layout_width="match_parent"
    android:layout_height="320dp"
    app:layout_behavior="@string/bottom_sheet_behavior"
    app:behavior_peekHeight="70dp">
  </RelativeLayout>
 </android.support.design.widget.CoordinatorLayout>

Error LogCat :

12-03 03:56:55.184 6750-6750 / com.example.aysha.todocln E / AndroidRuntime:FATAL EXCEPTION:main进程:com.example.aysha.todocln,PID:6750 java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.aysha.todocln / com.example.aysha.todocln.CalendarActivity}:显示java.lang.NullPointerException:尝试调用虚拟方法“无效android.support.v7.widget.RecyclerView.setLayoutManager(android.support .v7.widget.RecyclerView $ LayoutManager)'在Android.app上的android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)的空对象引用,android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) . ActivityThread.access $ 800(ActivityThread.java:151)在Android.os.Looper的android.app.Handler.dispatchMessage(Handler.java:102)上的android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1303) . 在java. java.lang.reflect.Method.invoke(Native Method)的android.app.ActivityThread.main(ActivityThread.java:5254)上循环(Looper.java:135) .lang.reflect.Method.invoke(Method.java:372)在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)在com.android.internal.os.ZygoteInit.main(ZygoteInit .java:698)引起:java.lang.NullPointerException:尝试在空对象上调用虚方法'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView $ LayoutManager)'在com.example.aysha.todocln.customCalendarView.updateCalendar(customCalendarView.java:103)在com.example.aysha.todocln.CalendarActivity.onCreate(CalendarActivity.java:87)参考在android.app.Activity.performCreate(活动 . 的java:5990)在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)在android.app.ActivityThread.access $ 800(ActivityThread.java:151)在android.app.ActivityThread $ H.handleMessage(ActivityThr) ead.java:1303)android.app.Handler.dispatchMessage(Handler.java:102)android.app.Looper.loop(Looper.java:135)android.app.ActivityThread.main(ActivityThread.java:5254) )at java.lang.reflect.Method.invoke(Native Method)at java.lang.reflect.Method.invoke(Method.java:372)at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java) :903)在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

2 回答

  • 0

    以这种方式更改您的代码

    LayoutInflater inflater = inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view =  inflater.inflate(R.layout.custom_calendar_view, null);
    
    // add Initialization Here
    
    header = (LinearLayout)view.findViewById(R.id.calendar_header);
    btnPrev = (ImageView)view.findViewById(R.id.calendar_prev_button);
    btnNext = (ImageView)view.findViewById(R.id.calendar_next_button);
    txtDate = (TextView)view.findViewById(R.id.calendar_date_display);
    grid = (RecyclerView)view.findViewById(R.id.calendarRecycler);
    
  • 0

    tnx很多你的帮助铁人我修复第二部分也只是改变你的代码

    inflater = inflater =(LayoutInflater)getContext() . getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom_calendar_view, this );

    而是使用null

相关问题