首页 > 解决方案 > android studio firebase 数据库:如何从子子节点获取数据

问题描述

我正在尝试从我的 firebase 数据库中检索颠簸数据,然后显示颠簸及其从数据库中检索到的信息。

问题是我的数据库包含子子,并且这个子子名称是基于位置的,所以我无法通过子子名称检索数据。

那么有没有一种方法可以检索所有子子名称?所以我可以通过 r 从子子项中检索数据来检索所有数据?

这是我的数据库

D b

这是我检索数据的代码

     private void showbumps() {
ref =FirebaseDatabase.getInstance().getReference().child("SpeedBump");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                List<SpeedBump> bumps = new ArrayList<>();
                bumps.clear();
                // get bumps info from DB
                
                for (DataSnapshot postSnapshot: snapshot.getChildren()) {

                    SpeedBump bump = postSnapshot.getValue(SpeedBump.class);

                    bumps.add(bump);

                   double bump_lat = bump.getLatitude();
                   double bump_long = bump.getLongitude();
                   String bump_type = bump.getType();
                   String bump_size = bump.getSize();

                    LatLng latLng = new LatLng(bump_lat,bump_long);
                    String bump_info = " type : "+ bump_type + " size : "+bump_size ;
// set height & width - apply style
                    int height = 130;
                    int width = 130;
                    Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
                    Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
                    BitmapDescriptor smallMarkerIcon = BitmapDescriptorFactory.fromBitmap(smallMarker);

                 //   BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.pin);
                    MarkerOptions marker = new MarkerOptions().position(latLng).title("Bump info").snippet(bump_info).icon(smallMarkerIcon);
// create marker for bumps
                    mMap.addMarker(marker);
                } }

代码没有显示任何凹凸。

标签: javaandroidfirebasefirebase-realtime-database

解决方案


您快到了。您只需要一个额外的循环来满足 JSON 中未知键的额外级别:

private void showbumps() {
    ref =FirebaseDatabase.getInstance().getReference().child("SpeedBump");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            List<SpeedBump> bumps = new ArrayList<>();
            bumps.clear();
            for (DataSnapshot locationSnapshot: snapshot.getChildren()) {
                for (DataSnapshot bumpSnapshot: locationSnapshot.getChildren()) {
                    SpeedBump bump = bumpSnapshot.getValue(SpeedBump.class);
                    ...

我发现为快照变量提供清晰的名称以指示它们捕获的数据的哪一部分是最有帮助的。


推荐阅读