我在for
android中有一个java
循环,它运行得很完美,但它只存储到循环中列表中的最后一项。我应该将user_id
和lesson_id
列入清单吗?我不知道从哪里开始,但这就是我所做的。逻辑工作正常,但它只保存两个变量中列表中的一个项目。
Android Studio代码:
// loop to add every user and lesson selected to watch
String user_id = null;
int lesson_id = 0;
for (int i = 0; i<attendees.size(); i++){
for (int j = 0; j<lesson_iDs.size(); j++){
user_id = attendees.get(i);
lesson_id = lesson_iDs.get(j);
}
}
// get the date for the classWatch
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
Date currentTime = localCalendar.getTime();
// to show in patient activity (sends to SQLite)
watch = new Watch(currentTime, user_id, lesson_id);
答案 0 :(得分:1)
这是正常的吗? 如果在循环外部使用user_id和lesson_id,则使用最后的值。 你不想做类似的事情:
// loop to add every user and lesson selected to watch
String user_id = null;
int lesson_id = 0;
// get the date for the classWatch
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
Date currentTime = localCalendar.getTime();
for (int i = 0; i<attendees.size(); i++){
for (int j = 0; j<lesson_iDs.size(); j++){
user_id = attendees.get(i);
lesson_id = lesson_iDs.get(j);
// to show in patient activity (sends to SQLite)
watch = new Watch(currentTime, user_id, lesson_id);
// Do something with watch...
}
}
答案 1 :(得分:0)
每次循环运行时,参与者.get(i)和lesson_iDs.get(j)的当前值都存储在两个变量(user_id,lesson_id)中,删除最后存储的值。如果要保留与会者和lesson_id列表的所有值,user_id和lesson_id必须是列表,并且在循环中,您必须向其添加attendees.get(i)和lesson_iDs.get(j)的当前值。 / p>
List<String> user_ids = new ArrayList<>();
List<Integer> lesson_ids = new ArrayList<>();
for (int i = 0; i<attendees.size(); i++){
for (int j = 0; j<lesson_iDs.size(); j++){
user_ids.add(attendees.get(i));
lesson_ids.add(lesson_iDs.get(j));
}
}