【问题标题】:Can't save a location due to null object error由于空对象错误,无法保存位置
【发布时间】:2018-04-05 15:37:48
【问题描述】:

我的目标是在 Firebase 数据库中保存和检索 Google 地图中的位置。当我尝试加载我应该保存位置的地图时,我的应用程序崩溃了。它不断返回错误:

java.lang.NullPointerException:尝试调用虚拟方法 空对象引用上的'double java.lang.Double.doubleValue()'

这是发生错误的代码部分:

profDatabase.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
            latt = snapshot.child("latitude").getValue(Double.class); //This is where the error happens
            longg = snapshot.child("longitude").getValue(Double.class);
            String stallname = snapshot.child("StallName").getValue().toString();

            LatLng newLocation = new LatLng(latt, longg);

            mMap.addMarker(new MarkerOptions()
              .position(newLocation)
              .title(stallname));
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }

这是我的数据库结构的屏幕截图,没有输入纬度和经度:

这是保存位置后的样子:

【问题讨论】:

    标签: android google-maps firebase firebase-realtime-database


    【解决方案1】:

    这意味着snapshot.child("latitude")中存储的数据不是有效的Double

    我能想到的最有可能的事情(没有看到您的实际数据)是您有一个字符串,其中 包含 值。在这种情况下,您可以通过以下方式获得双精度值:

    latt = Double.valueOf(snapshot.child("latitude").getValue(String.class));
    

    【讨论】:

    • 实际上还没有任何数据存储在那里,因为我必须先保存一个位置,这将是应该存储在数据库中的数据。但我无法保存位置,因为在我可以存储数据之前出现错误。
    • 我还不完全清楚(MCVE 会很有帮助)。但如果您想检查子节点是否存在,您可以使用:snapshot.child("latitude").exists()。请注意dataSnapshotsnapshot 本身将始终存在于您的onDataChange 中,因此您不需要检查这些exists()
    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多