【发布时间】:2020-05-03 15:55:36
【问题描述】:
每个日期都有多个日期和数据(课程和规模)。每个日期和数据都存储在一个唯一的键下。日期由日期选择器插入。
"Data":{
"K2ngvpioRUYF4bRM07Da5cbAjE53":{ //UID
"-M3jNjCuGdMCwt1Czpwz":{ //unique key
"Date":"2020-3-30",
"Course":"A",
"Scale":"3"
},
"-M5hxnQrCJdCUvRcMZJu":{
"Date":"2020-4-24",
"Course":"A",
"Scale":"3"
}
"-M3jQWxm7z0EQYgkVenX":{
"Date":"2020-4-29",
"Course":"B",
"Scale":"4"
},
"-M5hxn-rCJICUvRcMZJu":{
"Date":"2020-4-24",
"Course":"B",
"Scale":"2"
}
}
}
我想根据每月的课程计算总秤数。对于比例,如果数字为 3,则表示 0.6。如果数字为 2,则表示 0.4。如果数字是 4,则表示 0.8。因此,对于课程 A,总数为 1.2(0.6+0.6)。对于课程 B,总数为 1.2 (0.8+0.4)。
Calendar mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int month = mCalendar.get(Calendar.MONTH);
final int[] Currmonth = {month + 1}; //this is array because there are other method using this but unnecessary for this question
int lastDay = mCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay=1;
String start=year+"-"+Currmonth[0]+"-"+firstDay;
String end=year+"-"+Currmonth[0]+"-"+lastDay;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users Mood");
Query range = ref.child(user.getUid()).orderByChild("Date").startAt(start).endAt(end);
range.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ArrayList<String> courses=new ArrayList<>();
Map<String, Double> hm = new HashMap<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String course=ds.child("Course").getValue(String.class);
courses.add(course);
String scale=ds.child("Scale").getValue(String.class);
for(String i :courses) {
double num=0;
if (hm.get(i).equals("1")) {
num=0.2;
}else if(hm.get(i).equals("2")){
num=0.4;
}else if(hm.get(i).equals("3")){
num=0.6;
}else if(hm.get(i).equals("4")){
num=0.8;
}else if(hm.get(i).equals("5")){
num=1;
}
double total = hm.containsKey(course) ? hm.get(course) : 0;
total += num;
hm.put(course, total);
}
}
for(String key:hm.keySet()) {
Log.d("tag", key+hm.get(key));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
在这种情况下,查询是从当月的开始日期到当月的结束日期。映射两个孩子的逻辑是不正确的。我认为 hashmap 不适合这种情况,因为同一课程的相同比例的数据可能很少(例如,有两个相同的数据,课程 A 比例为 3 或 num 0.6)。请帮我纠正我的逻辑。
【问题讨论】:
标签: java android firebase-realtime-database