【问题标题】:Checking if a field exists in Firebase real time database检查 Firebase 实时数据库中是否存在字段
【发布时间】:2019-11-07 18:19:41
【问题描述】:

我在我的 Android 应用中使用 Firebase 数据库。这是子Users的结构:

正如您在图片中看到的那样,有些项目具有名为 imageURL 的字段,而其他项目没有名为 imageURL 的字段。

这是我的应用程序中的一段代码,我从字段imageURL 获取值:

fuser = FirebaseAuth.getInstance().getCurrentUser();
        reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                com.mpidesarrollo.buju.Model.User user = dataSnapshot.getValue(User.class);
                username.setText(user.getUsername());


                if (user.getImageURL().equals("default")){
                    image_profile.setImageResource(R.mipmap.ic_launcher);
                } else {
                    Glide.with(getApplicationContext()).load(user.getImageURL()).into(image_profile);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

如果数据库中不存在字段 imageURL,我会在以下行出现异常:

if (user.getImageURL().equals("default")){

因为字段 imageURL 不存在。

如何检查字段是否存在以避免异常?

【问题讨论】:

  • .getReference("Users").child(fuser.getUid()).orderbyChild("imageURL").equal("default")

标签: java android firebase firebase-realtime-database


【解决方案1】:

如何检查字段是否存在以避免异常?

有两种方法可以解决这个问题。第一个是检查 imageURL 属性是否存在:

if(dataSnapshot.child("imageURL").exists()) {
    //Do your logic
}

或者您可以检查imageURL 字段是否为空:

if(user.getImageURL() != null) {
    //Do your logic
}

【讨论】:

  • 您将如何决定使用一种方式或另一种方式?
  • @auspicious99 第一个检查单个属性的值是否存在,而第二个检查整个对象中存在的字段的值是否不为空。
  • 谢谢亚历克斯。我在考虑性能等方面;发布stackoverflow.com/questions/69258532/… 并得到答案。再次感谢
【解决方案2】:

由于变量为空而出现异常,您正在尝试检查此行的值。

if (user.getImageURL().equals("default"))

如果您的模型中有字段并且该字段在 firebase 中不可用,那么这将返回 null。

if(user.getImageURL()!=null) //checking field is available or not
{ 
    // imageURL exist in the database
    if (user.getImageURL().equals("default")){
                image_profile.setImageResource(R.mipmap.ic_launcher);
            } else {
                Glide.with(getApplicationContext()).load(user.getImageURL()).into(image_profile);
            }
}
else{
    // imageURL doesn´t exist in the database
}

【讨论】:

    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    相关资源
    最近更新 更多