如何使用模型类从Firebase数据库添加数据

时间:2018-12-27 11:51:43

标签: android firebase firebase-realtime-database

如何使用模型类从firbase数据库中获取数据?

enter image description here

2 个答案:

答案 0 :(得分:1)

您的模型,根据您要检索的数据应该是这样的(假设您只想要键和单词)

 public class Model {

    private String key;
    private String word;
    private String baseText;
    private String mainText;
    private String type;
    private String url;

    public Model() {
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public String getBaseText() {
        return baseText;
    }

    public void setBaseText(String baseText) {
        this.baseText = baseText;
    }

    public String getMainText() {
        return mainText;
    }

    public void setMainText(String mainText) {
        this.mainText = mainText;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

然后,您可以获取数据

ref.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    Model model = dataSnapshot.getValue(Model.class);
    log.d("Key: "+model.getKey() + " word: " + model.getWord());
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    System.out.println("The read failed: " + databaseError.getCode());
  }
});

ref在您要提取数据的节点上的DatabaseReference

请参阅此链接

https://firebase.google.com/docs/database/admin/retrieve-data?hl=en#section-start

答案 1 :(得分:1)

让ref为您的DatabaseReference,然后为addValueEventListener

示例:

ref.addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot){
       DataModel model = dataSnapshot.getValue(DataModel.class);
    }
}

任何类都可以完成相同的操作,例如,如果您想获得输出

String -> getValue(String.class)
Integer -> getValue(Integer.class)