我试图使用for循环动态创建RecyclerView但是我在这个例子中得到NPE并且我不确定为什么(我确定我&# 39; m俯视小东西 - 如果从for循环中删除它(并为单个实例调整它),代码可以工作,所以我不确定错误的确切内容。
任何建议都表示赞赏。
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void Notification.setCategory(java.lang.String)' on a null object reference
for(int l=1; l< body_list.size(); l++){
List<Notification> notifications = new ArrayList<>();
Notification[] notification = new Notification[N];
notification[l].setCategory("TEST");
notification[l].setTimeSince("now");
notification[l].setTitle(title_list.get(l));
notification[l].setBody(body_list.get(l));
notifications.add(notification[l]);
mAdapter1 = new NotificationDataAdapter(notifications);
}
// List<Notification> notifications2 = new ArrayList<>();
// Notification notification2 = new Notification();
// notification2.setCategory("Test");
// notification2.setTimeSince("1 Day Ago");
// notification2.setTitle("Marilyn Ferguson");
// notification2.setBody("Lorem ipsum dolor sit amet, consectetur.");
// notifications.add(notification2);
// mAdapter2 = new NotificationDataAdapter(notifications2);
答案 0 :(得分:1)
您必须先使用通知实例填充通知数组,然后才能访问它们。
你错过了
notification[l] = new Notification();
在你做之前
notification[l].setCategory("TEST");
你可能根本不需要阵列......你可以这样做:
List<Notification> notifications = new ArrayList<>();
for(int l = 1; l< body_list.size(); l++){
Notification notification = new Notification();
notification.setCategory("TEST");
notification.setTimeSince("now");
notification.setTitle(title_list.get(l));
notification.setBody(body_list.get(l));
notifications.add(notification);
}
mAdapter1 = new NotificationDataAdapter(notifications);