首页 > 解决方案 > 我在 addValueEventListener 中的 dataSnapshot 中遇到错误

问题描述

我的代码中有这个事件监听器。我想获取firebase中的值。但是我的变量'ds'在我的 . getValue()方法。`

ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                showData(dataSnapshot);
            }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

private void showData(DataSnapshot dataSnapshot) {

    for (DataSnapshot ds: dataSnapshot.getChildren());

    UserInformation uInfo = new UserInformation();

    uInfo.setAddress(ds.child(userID).getValue(UserInformation.class).getAddress());

    uInfo.setDate(ds.child(userID).getValue(UserInformation.class).getDate());

    uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName());

    uInfo.setPhone(ds.child(userID).getValue(UserInformation.class).getPhone());

    uInfo.setQuantity(ds.child(userID).getValue(UserInformation.class).getQuantity());

    Log.d(TAG, "showData: address" + uInfo.getAddress());

    Log.d(TAG, "showData: date" + uInfo.getDate());

    Log.d(TAG, "showData: name" + uInfo.getName());

    Log.d(TAG, "showData: phone" + uInfo.getPhone());

    Log.d(TAG, "showData: quantity" + uInfo.getQuantity());

` 我收到错误“找不到符号 ds”

标签: java

解决方案


你正在立即取消你的 for 循环:

for (DataSnapshot ds: dataSnapshot.getChildren());

您需要为您的 for 循环提供一个代码块,例如:

for (DataSnapshot ds: dataSnapshot.getChildren()) {
    // do stuff with ds here
}

推荐阅读