【问题标题】:datasnapshot.getvalue() does not work and crashes app [duplicate]datasnapshot.getvalue() 不起作用并使应用程序崩溃 [重复]
【发布时间】:2018-09-15 11:05:42
【问题描述】:

我正在尝试以 BusInformation.class 的形式从 firebase 实时数据库中获取数据。但是此时我的应用程序在设置快照的类类型时崩溃了:ds.getValue(BusInformation.class);

我收到以下错误:

com.google.firebase.database.DatabaseException: Class com.example.muzammil.bustracking.app_classes.BusInformation does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
        at com.google.android.gms.internal.firebase_database.zzku.zza(Unknown Source)
        at com.google.android.gms.internal.firebase_database.zzkt.zzb(Unknown Source)
        at com.google.android.gms.internal.firebase_database.zzkt.zza(Unknown Source)
        at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)

以下是 BuInformation.java 类的代码:

public class BusInformation {
    private String id, username,phone;
    private LatLng position;
    private String destination;

    public BusInformation(String id, String username, String phone,  String destination,LatLng position) {
        this.id = id;
        this.username = username;
        this.phone = phone;
        this.position = position;
        this.destination = destination;
    }
}

在 Firebase 数据库中,数据完全以这种形式存在。

从firebase获取数据的代码:

 public void getUpdatesFromFirebase(DataSnapshot dataSnapshot){
        for(DataSnapshot ds : dataSnapshot.getChildren()){
            if(ds.exists()) {
                busInfo = ds.getValue(BusInformation.class);  //App crashes at this point

            }

        }
    }

任何人请告诉我代码有什么问题...

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    BusInformation does not define a no-argument constructor.

    手动为其添加无参数构造函数:public BusInformation(){}

    你的班级应该是这样的:

    public class BusInformation {
        private String id, username,phone;
        private LatLng position;
        private String destination;
    
        //no-argument constructor
        public BusInformation(){}
    
        public BusInformation(String id, String username, String phone,  String destination,LatLng position) {
            this.id = id;
            this.username = username;
            this.phone = phone;
            this.position = position;
            this.destination = destination;
        }
    }
    

    【讨论】:

    • 感谢您的回复。异常现在更改为:com.google.firebase.database.DatabaseException:com.google.android.gms.maps.model.LatLng 类未定义无参数构造函数。如果您使用 ProGuard,请确保未剥离这些构造函数。
    • 这是另一个问题。如果它回答了您的问题,您应该接受一个答案。关于以下问题,请查看this 答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2013-09-17
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 2012-05-20
    相关资源
    最近更新 更多