如何从Android Firebase中的“餐厅”获取子级值?我得到空值

时间:2018-07-05 15:21:50

标签: java android firebase firebase-realtime-database

如何从android Firebase中的“餐厅”获取子级值?我得到空值

    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    database.getReference().child("restaurants").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<RestaurantDetails> foodItems = new ArrayList<>();
            Iterable<DataSnapshot> iterable = dataSnapshot.getChildren();
            for(DataSnapshot child : iterable){
                foodItems.add(
                        new RestaurantDetails(
                                child.getKey(),
                                child.child("name").getValue().toString(),
                                selectedCategory,
                                Double.parseDouble(child.child("ratings").getValue().toString()),
                                child.child("imageurl").getValue().toString(),
                                child.child("description").getValue().toString(),
                                Integer.parseInt(child.child("count").getValue().toString())
                        )
                );
                Log.d(child.getKey(),child.getValue().toString());
            }
            recyclerView.setAdapter(shoplistItemArrayAdapter);
            progressDialog.cancel();
        }

enter image description here

1 个答案:

答案 0 :(得分:0)

因为您是从数据库中获取的,所以无需创建RestaurantDetails类的新对象。因此,为解决此问题,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference restaurantsRef = rootRef.child("restaurants");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            RestaurantDetails restaurantDetails = ds.getValue(RestaurantDetails.class);
            Log.d("TAG", restaurantDetails.getDescription());
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
restaurantsRef.addListenerForSingleValueEvent(valueEventListener);

您的logcat中的输出将是:

Biryani,Chinese,North Indian,South India
Indian,Chines,Byran

如果要使用String类而不是RestaurantDetails,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference restaurantsRef = rootRef.child("restaurants");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String description = ds.child("description").getValue(String.class);
            Log.d("TAG", description);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
restaurantsRef.addListenerForSingleValueEvent(valueEventListener);

输出将相同。