我在Firebase中有以下结构:
"surveys" : {
"-Kq2r56mEoZ0LDBbi47W" : {
"name" : "Survey 1",
"questions" : [ {
"name" : "Question 1"
},{
"name" : "Question 2"
},{
"name" : "Question 3"
} ]
}
以下是相应的Java类 Survey.java :
public class Survey {
private String name;
private ArrayList<String> questions = new ArrayList<>();
public Survey(){}
// Getters and setters
...
}
在我的活动中,我试着像这样得到调查元素:
final DatabaseReference surveysReference = database.getReference(FirebaseReferences.SURVEY_REFERENCE).child(currentId);
surveysReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
SurveyDao survey = snapshot.getValue(SurveyDao.class);
surveyList.add(survey);
}
@Override
public void onCancelled(DatabaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
但由于结构不正确,我不断收到错误。 我怎样才能得到我的问题&#34;列出并将其保存在我的Survey对象中?
提前致谢
答案 0 :(得分:0)
包含另一个对象,即通过Survey类的Kq2r56mEoZ0LDBbi47W,如
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Surveys {
@SerializedName("-Kq2r56mEoZ0LDBbi47W")
@Expose
private Kq2r56mEoZ0LDBbi47W kq2r56mEoZ0LDBbi47W;
public Kq2r56mEoZ0LDBbi47W getKq2r56mEoZ0LDBbi47W() {
return kq2r56mEoZ0LDBbi47W;
}
public void setKq2r56mEoZ0LDBbi47W(Kq2r56mEoZ0LDBbi47W kq2r56mEoZ0LDBbi47W) {
this.kq2r56mEoZ0LDBbi47W = kq2r56mEoZ0LDBbi47W;
}
}
和Kq2r56mEoZ0LDBbi47W类包含问题列表
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Kq2r56mEoZ0LDBbi47W {
@SerializedName("name")
@Expose
private String name;
@SerializedName("questions")
@Expose
private List<Question> questions = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
}
和问题类是:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Question {
@SerializedName("name")
@Expose
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
答案 1 :(得分:0)
问题应为:
List<Map<String, String>>
而不是:
List<String>
您还可以创建问题类:
@IgnoreExtraProperties
public class Question {
public String name;
public Question() {
// Default constructor required for calls to DataSnapshot.getValue(Question.class)
}
public Question(String name) {
this.name = name;
}
}
它将是:
List<Question>
答案 2 :(得分:0)
如果您的Survey类是这样的:
public class Survey {
private String name;
private ArrayList<String> questions = new ArrayList<>();
public Survey(){}
// Getters and setters
...
}
然后你的firebase结构应该是这样的:
"surveys" : {
"-Kq2r56mEoZ0LDBbi47W" : {
"name" : "Survey 1",
"questions" : [
{
0 : "Question 1"
},{
1 : "Question 2"
},{
2 : "Question 3"
}
]
}
记住arrayList或list,就像一个Map,但使用integer
作为索引。它从0开始