如何从适配器获取项目并将其存储在列表中?

时间:2018-01-13 06:05:21

标签: android android-layout arraylist android-recyclerview android-adapter

我从adapter得到的列表工作正常。现在,我需要在按钮点击时将其存储在MainActivity的列表中。但我正在崩溃,

  

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void com.savedayreq.RoutePlanDayRequests.setPartnerId(java.lang.String)'                                                                                 at com.view.RoutePlanVisitChangeActivity $ 2.onClick(RoutePlanVisitChangeActivity.java:92)

第92行是此代码。

 submitChangeRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter = (RoutePlanVisitChangeAdapter) mRecyclerView.getAdapter();
                List<RoutePlanDayRequests> routePlanDayRequests=null;
                RoutePlanDayRequests requests = null;
                for (int i = 0; i < adapter.getItemCount(); i++) {
                    Retailers selectedView = adapter.getItem(i);

                    View dataView  = mRecyclerView.getChildAt(i);
                    Spinner toDaySpinner = (Spinner) dataView.findViewById(R.id.to_day);
                      //i can print this oldDay,newDay, msisdn line..
                    String oldDay = selectedView.getRoutePlanDayOfWeek(); 
                    String newDay = toDaySpinner.getSelectedItem().toString();
                    String msisdn = selectedView.getMsisdn(); //i can also print this line in log. 
        //***But I am getting crash from this line no 92..*** 
                    requests.setPartnerId(selectedView.getMsisdn());
                    requests.setParentPartnerId(selectedView.getMsisdn());
                    requests.setApproverId("1");
                    requests.setStatus("0");
                    requests.setRetailerPrmId(selectedView.getMsisdn());
                    requests.setOldDay(oldDay);
                    requests.setNeweDay(newDay);
                    routePlanDayRequests.add(requests); 
                    updateServiceList(AppUtils.getMsisdn(mSharedPreferences),routePlanDayRequests);
}

3 个答案:

答案 0 :(得分:1)

您没有初始化这两个对象。它们被设置为null。

List<RoutePlanDayRequests> routePlanDayRequests=null;
RoutePlanDayRequests requests = null;

像这样初始化它们 -

List<RoutePlanDayRequests> routePlanDayRequests= new Arraylist();
RoutePlanDayRequests requests = new RoutePlanDayRequests();

您需要一个公共构造函数RoutePlanDayRequests。在你RoutePlanDayRequests类中添加这个构造函数。

public RoutePlanDayRequests() {
}

答案 1 :(得分:0)

您应该从RoutePlanDayRequests创建一个新对象,然后您可以设置此对象的变量 改变这一行:

 RoutePlanDayRequests requests = null

RoutePlanDayRequests requests = new RoutePlanDayRequests()

如果RoutePlanDayRequests具有空的构造函数

答案 2 :(得分:0)

初始化RoutePlanDayRequests课程

  RoutePlanDayRequests requests = new RoutePlanDayRequests();