代码之家  ›  专栏  ›  技术社区  ›  Hussam

无法从firebase数据库快照读取对象

  •  0
  • Hussam  · 技术社区  · 7 年前

    我试着从Firebase读取经纬度,并在这些位置放置标记。但似乎有一些错误崩溃的应用程序,我无法找到,即使在Logcat。尝试在每条语句后放置一些检查日志,发现问题出现在我尝试从数据库快照将值放入类对象的地方。我正在尝试使用循环从快照中获取所有对象。这是我的数据库结构。 enter image description here

    我的Maps活动代码,我试图将值从数据库快照放到类对象中。

    //reading stations from database
    List<Stations> stations;
     mDatabase = FirebaseDatabase.getInstance().getReference().child("STATIONS");
    
        ValueEventListener stationListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                //found out that error is here
                for(DataSnapshot stationsSnapshot: dataSnapshot.getChildren()){
                    stations.add(stationsSnapshot.getValue(Station.class));
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.i("Station Read[ERROR]",databaseError.getMessage());
            }
        };
        mDatabase.addListenerForSingleValueEvent(stationListener);
    

    station class code location class code .

    在从firebase获取的地图上标记位置的代码。

        //Placing all station data on Maps
        for(int i=0 ; i<stations.size() ; i++){
            LatLng location = new LatLng(stations.get(i).getLocation().getLatitude(),
                    stations.get(i).getLocation().getLongitude());
            mMap.addMarker(new MarkerOptions().position(location).title(stations.get(i).getName()));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
        }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   uneq95    7 年前

    初始化站点列表。

    List<Stations> stations= new ArrayList<>();
    

    添加标记的逻辑在我看来是正确的。只要把它放在正确的地方,就像Momen说的那样,应该可以。

        2
  •  0
  •   Momen Zaqout    7 年前

    Stations 必须和firebase中的物体一样。就像那样

    public class Stations{
    
    public Location location;
    public String name
    
    //..getter and setter
    
    public static class Location{
    public double latitude;
    public double  longitude;
    
    //..getter and setter
    
    }
    }
    

    场地必须是公共的

    2-初始化arraylist

    List<Stations> stations=new Arraylist();