【问题标题】:could not be able to get data from list/array of firebase realtime database无法从 firebase 实时数据库的列表/数组中获取数据
【发布时间】:2016-07-30 05:54:54
【问题描述】:

我一直在努力寻找解决问题的方法,即我想从此数据库架构中获取数据

{
      "brs" : {
        "route": [
          {
            "routeDestination": "DDDD1",
            "routeOrigin": "OOOO1",
            "bus" : {
                "busArrivalTime" : "created_at_timestamp",
                "busDepartureTime" : "created_at_timestamp",
                "busName" : "SOME NAME",
                "busSeatCost" : "0000",
                "busTotalSeats" : "000",
                "reservations": [
                  {
                    "reservationId": 1,
                    "reservationDate": "Wed Jul 06 23:54:56 EDT 2016",
                    "seats": [
                      {                
                        "seatNumber": 1
                      },
                      {               
                        "seatNumber": 2
                      }
                    ]
                  }
                ] 
            }            
          },
          {
            "routeDestination": "DDDD2",
            "routeOrigin": "OOOO2",
            "bus" : {
                "busArrivalTime" : "created_at_timestamp",
                "busDepartureTime" : "created_at_timestamp",
                "busName" : "SOME NAME",
                "busSeatCost" : "0000",
                "busTotalSeats" : "000",
                "reservations": [
                  {
                    "reservationId": 1,
                    "reservationDate": "Wed Jul 06 23:54:56 EDT 2016",
                    "seats": [
                      {                
                        "seatNumber": 1
                      },
                      {               
                        "seatNumber": 2
                      }
                    ]
                  }
                ] 
            }            
          },
          {
            "routeDestination": "DDDD3",
            "routeOrigin": "OOOO3",
            "bus" : {
                "busArrivalTime" : "created_at_timestamp",
                "busDepartureTime" : "created_at_timestamp",
                "busName" : "SOME NAME",
                "busSeatCost" : "0000",
                "busTotalSeats" : "000",
                "reservations": [
                  {
                    "reservationId": 1,
                    "reservationDate": "Wed Jul 06 23:54:56 EDT 2016",
                    "seats": [
                      {                
                        "seatNumber": 1
                      },
                      {               
                        "seatNumber": 2
                      }
                    ]
                  }
                ] 
            }            
          }
        ]
      }
    }

使用此代码

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference myRef = firebaseDatabase.getReference("route");            
        try {
            // Read from the database             
            myRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {                      
                    GenericTypeIndicator<List<String>> t = new GenericTypeIndicator<List<String>> () {};
                    List<String> routes = dataSnapshot.getValue(t);                        
                    if( routes == null ) {
                        Snackbar.make(view, "Returned No Result" , Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();
                    }
                    else {
                        Snackbar.make(view, "The routes Size is " + routes.size(), Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();

                    }                       
                }

                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Log.w("BUS_TAG", "Failed to read value.", error.toException());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
});

通过上面的代码,我只得到了 Snack bar 的结果 Returned No Result

更新

我已经按照 @silverFoxA 的建议进行了尝试,并简单地制作了 POJO

public class Route {

    private String routeDestination;
    private String routeOrigin;

    public String getRouteDestination() {
        return routeDestination;
    }

    public void setRouteDestination(String routeDestination) {
        this.routeDestination = routeDestination;
    }

    public String getRouteOrigin() {
        return routeOrigin;
    }

    public void setRouteOrigin(String routeOrigin) {
        this.routeOrigin = routeOrigin;
    }
}

并尝试了下面答案中给出的代码

DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("routes");
Toast.makeText(MainActivity.this, "Clicked ---- ", Toast.LENGTH_LONG).show();
final List<Route> routes = new CopyOnWriteArrayList<Route>();
try {
    // Read from the database
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("The routes Size is " + dataSnapshot.getChildrenCount());
            Snackbar.make(view, "The routes Size is " + routes.size(), Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
            for (DataSnapshot route : dataSnapshot.getChildren()) {
                System.out.println("from " + route.child("routeOrigin").getValue() +
                        " to " + route.child("routeDestination").getValue());
            }            
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w("BUS_TAG", "Failed to read value.", error.toException());
        }
    });

现在我得到路线大小为0的结果。

我也尝试过不同的方式

DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("brs");
Toast.makeText(MainActivity.this, "Clicked ---- ", Toast.LENGTH_LONG).show();
final List<Route> routes = new CopyOnWriteArrayList<Route>();

myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Route route = dataSnapshot.getValue(Route.class);
        routes.add(route);
        Snackbar.make(view, "The routes Size is " + routes.size(), Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

这段代码导致异常

07-25 06:26:33.792 5861-5861/? E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.rhcloud.escot.bsr, PID: 5861
 com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type com.rhcloud.escot.bsr.Route
     at com.google.android.gms.internal.zzalq.zzd(Unknown Source)
     at com.google.android.gms.internal.zzalq.zzb(Unknown Source)
     at com.google.android.gms.internal.zzalq.zza(Unknown Source)
     at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
     at com.rhcloud.escot.bsr.MainActivity$2$2.onChildAdded(MainActivity.java:94)
     at com.google.android.gms.internal.zzahh.zza(Unknown Source)
     at com.google.android.gms.internal.zzajh.zzctc(Unknown Source)
     at com.google.android.gms.internal.zzajk$1.run(Unknown Source)
     at android.os.Handler.handleCallback(Handler.java:815)
     at android.os.Handler.dispatchMessage(Handler.java:104)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5631)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
07-25 06:26:33.871 6417-6417/? E/SysUtils: ApplicationContext is null in ApplicationStatus

如何获取路线列表/数组并对其进行迭代,在这种情况下我需要一些帮助。

【问题讨论】:

  • 我建议使用 POJO
  • 您可以使用 String 然后解析数据,或者接受您选择的自定义数据类型来克服解析延迟,而不是接受 onDataChange 中的数据快照对象。让我试试,很快就会更新你。
  • @VV 请问有什么进展吗?

标签: java android firebase firebase-realtime-database


【解决方案1】:

尝试使用此数据库的最后一个解决方案:

DatabaseReference myRef = FirebaseDatabase.getInstance().child("brs").child("route");

or

DatabaseReference myRef = FirebaseDatabase.getInstance().child("brs/route");

【讨论】:

    【解决方案2】:

    您实际上不太可能在 Firebase 中存储数组。更有可能的是,它实际上是一个关联数组,其中的键可能是整数。

    使用 Firebase 数据库时,通常的做法是不使用数组并将所有内容都视为 Map。在您的情况下,这可能会解决您的问题:

    public void onDataChange(DataSnapshot snapshot) {                      
        System.out.println("The routes Size is " + snapshot.getNumChildren());
        for (DataSnapshot route: snapshot.getChildren()) {
            System.out.println("from "+route.child("routeOrigin").getValue()+
                               " to "+route.child("routeDestination").getValue());
        }
    }
    

    参见Android reference docs 中的getChildrenCount()getChildren()

    正如 silverFoxA 评论的那样,强烈建议您创建一个表示路由的 Java 类。处理 DataSnapshot 或(甚至更糟)类型安全的 ListMap 实例会很快让最顽固的开发人员发疯。

    【讨论】:

    • 男人!我仍在努力解决一些问题,我已经更新了我的问题,请看一下并给我一个解决方案。正如您所说的 “您实际上不太可能在 Firebase 中存储一个数组。更有可能它实际上是一个关联数组,它们的键可能是整数。” ,你能建议我为这个应用程序使用不同的架构吗?你真好!
    【解决方案3】:

    嘿,在您的第二次更新更改中,您使用了错误的密钥:

       DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("routes");
    
    but in your json object its "route".
        ArrayList<Route> listRoutes = new ArrayList();
        DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("route");
    
        try {
    
            myRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
    
                    for (DataSnapshot routeSnapshot:dataSnapshot.getChildren()){
                    Route route = routeSnapshot.getValue(Route.class);
                    //save each route in arraylist
                    listRoutes.add(route);
    
    
            }       
                }
    
                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Log.w("BUS_TAG", "Failed to read value.", error.toException());
                }
            });
    

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 2017-10-13
      相关资源
      最近更新 更多