无法获取数组列表中的count元素

时间:2019-05-17 09:29:36

标签: java android arraylist

在此示例中,我有一个Firebase数据库,因此可以从数据库中获取元素和键。我使用了一些库和函数来处理数据库。问题出在我获取数据并将其放到名为comments_keys的ArrayList中之后,我使用一个循环来打印其中的项目,然后连续打印四次I/Get_KEY:: comments

现在为什么不打印Count等于4?

我想获得ArrayList内的项目数的值。我怎么做?

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot child: dataSnapshot.getChildren()) {
        HashMap < String,
        HashMap < String,
        HashMap < String,
        String >>> values = (HashMap < String, HashMap < String, HashMap < String, String >>> ) child.getValue();

        ArrayList < String > comments_keys = new ArrayList < String > (values.keySet());
        int Count = 0;

        for (String k: comments_keys) {
            players.put(k, String.valueOf(values.get(k)));
            Log.i("GetValues :", players.values().toString());
            Log.i("Get_KEY: ", k);
            Count += 1;
        }
        Log.i("GetCount) : ", String.valueOf(Count));
    }
}
// Log Cat Get_KEY: 
05-17 11:09:37.455 25024-25024/com.ahmedcomm.firebaseapp I/Get_KEY:: comments
05-17 11:09:37.455 25024-25024/com.ahmedcomm.firebaseapp I/Get_KEY:: comments
05-17 11:09:37.455 25024-25024/com.ahmedcomm.firebaseapp I/Get_KEY:: comments
05-17 11:09:37.455 25024-25024/com.ahmedcomm.firebaseapp I/Get_KEY:: comments

// Log Cat Get_KEY: 
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetValues :: [{-LeT9FJNoQaGIz04t5Ux={status=1, rate=4, comment=yes}}]
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetValues :: [{-LeTA3vsxwsKuhvcITVE={status=0, rate=2, comment=i don't like it}, -LeWdgceDbsf4eKkQW6B={status=0, rate=3, comment=okys}}]
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetValues :: [{-LeTAVMVV2aZcpZ3UelP={status=1, rate=5, comment=i like it}}]
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetValues :: [{-LeTBX4SIWPAoYzCdgCq={status=1, rate=5, comment=ملعب ممتاز}, -LeTCUtavtH3HzNc_CBY={status=0, rate=3, comment=not pad}, -LeTCDwJ9Ptc-DC9RMxE={status=1, rate=5, comment=good}}]

// Log Cat GetCount:
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetCount) :: 1
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetCount) :: 1
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetCount) :: 1
05-17 11:23:38.005 25410-25410/com.ahmedcomm.firebaseapp I/GetCount) :: 1

1 个答案:

答案 0 :(得分:2)

我不知道您为什么要使代码复杂化。这种怪异的铸造有什么作用?

(HashMap < String, HashMap < String, HashMap < String, String >>> ) child.getValue();

为简化所有操作,您可以执行以下操作:

class MyClass {
   // This is your model that matches the data in Firebase
   // put here the properties as in DB
   // for example
   String name;
   // and so on.
}

List<MyClass> myClassList = new ArrayList<>();

for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
 MyClass myClass = snapshot.getValue(MyClass.class);
 myClassList.add(myClass);
}

int size = list.size(); // this is the count