簡體   English   中英

自定義控件中的recyclerview和gridview空指針異常

[英]recyclerview and gridview null pointer exception in custom control

我按照本教程並應用了一些更改,並在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>

錯誤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:嘗試調用虛方法'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support。 v7.widget.RecyclerView $ LayoutManager)'在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)上的android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)上的空對象引用,位於android.app.ActivityThread .access $ 800(ActivityThread.java:151)位於android.app.Loper.loop的android.app.A.運行時,android.O. Hand.Mhaage(Handler.java:102)上的android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1303) (Looper.java:135)在java.l的java.lang.reflect.Method.invoke(Native Method)的android.app.ActivityThread.main(ActivityThread.java:5254)上 ang.reflect.Method.invoke(Method.java:372)at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:903)at 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)' at com.example.aysha.todocln.customCalendarView.updateCalendar(customCalendarView.java:103)at com.example.aysha.todocln.CalendarActivity.onCreate(CalendarActivity.java:87)at android.app.Activity.performCreate(Activity.java) :5990)android.app.Anstrumentation.callActivityOnCreate(Instrumentation.java:1106)android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)at 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)

以這種方式更改您的代碼

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);

tnx很多你的幫助鐵人我修復第二部分也只是改變你的代碼

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

而是使用null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM