无法从firebase实时数据库的列表/数组中获取数据

时间:2016-07-24 01:36:09

标签: java android firebase firebase-realtime-database

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

{
      "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说返回无结果

更新

我按照 @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

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

3 个答案:

答案 0 :(得分:1)

尝试使用此db的最后一个解决方案:

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

or

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

答案 1 :(得分:0)

您实际上不太可能在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实例会迅速推动即使是最顽固的开发人员疯狂。

答案 2 :(得分:0)

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

   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());
            }
        });