一个菜鸟问题,但是为这种情况建立循环的最佳方法是什么? Suppose I have this table. 我想计算每天创建的记录数,并将每个不同的日期及其记录数存储在数组列表中。如果日期中没有任何记录(例如8/25),则该日期仍应以0计数存储。
数据是从Realm表中提取的,因此SQL查询不起作用。
ArrayList<Date> days = new ArrayList<Date>();
ArrayList<Integer> recordsPerDay = new ArrayList<Integer>();
int count = 0;
for(countresults = 0; countresults <= results.size(); countresults++){
if(tblProposalCorporate.getDateCreated()!=lastWeek)
{
days.add(tblProposalCorporate.getDateCreated());
count = 0;
}
if (tblProposalCorporate.getDateCreated()==lastWeek)
{
days.add(tblProposalCorporate.getDateCreated());
count+=1;
}
}
答案 0 :(得分:0)
实际上非常简单,只需从Realm获取最小和最大日期即可。
Date minimumDate = realm.where(Proposal.class).mininumDate("dateCreated");
Date maximumDate = realm.where(Proposal.class).maximumDate("dateCreated");
然后,您可以将这些日期设置为零时,分,秒和毫秒:
Calendar calendar = Calendar.getInstance();
calendar.setTime(minimumDate);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
minimumDate = calendar.getTime();
calendar.setTime(maximumDate);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
maximumDate = calendar.getTime();
现在您要做的就是迭代日期并执行查询以获取数据计数
Map<Date, Long> counts = new LinkedHashMap<>();
for(Date iterDate = new Date(minimumDate); iterDate.getTime() <= maximumDate.getTime(); ) {
calendar.setTime(iterDate);
calendar.add(Calendar.DAY_OF_MONTH, 1);
Date nextDay = calendar.getTime();
counts.put(iterDate, realm.where(Proposal.class).greaterThanOrEqualTo("dateCreated", iterDate).lowerThan("dateCreated", nextDay).count());
iterDay.setTime(nextDay.getTime());
}