Reputation: 177
I am writing an Android app using Firebase for cloud database. Its basically a multiple choice survey question app. Imported to Firebase I had
{
"multiple_choice" : {
"-K2222222222" : {
"question" : "Question text",
"opt1" : "answer 1",
"opt2" : "answer 2",
"opt3" : "answer 3"
}
}
}
I add a MultipleChoice class like so
public class MultipleChoice {
private String id;
private String question;
private String opt1;
private String opt2;
private String opt3;
public MultipleChoice() {
}
public MultipleChoice(String question, String opt1, String opt2, String opt3) {
this.question = question;
this.opt1 = opt1;
this.opt2 = opt2;
this.opt3 = opt3;
}
public void setQuestion(String question) {
this.question = question;
}
public String getOpt1() {
return opt1;
}
public void setOpt1(String opt1) {
this.opt1 = opt1;
}
public String getOpt2() {
return opt2;
}
public void setOpt2(String opt2) {
this.opt2 = opt2;
}
public String getOpt3() {
return opt3;
}
public void setOpt3(String opt3) {
this.opt3 = opt3;
}
public String getQuestion() {
return question;
}
}
which allows me to retrieve this data in the main class using Firebase references.
Now I want to make it like an array of options although FB doesn't literally work that way, so it can take any number of options instead of a fixed 3 or whatever. This json file loaded into FB
{
"multiple_choice" : {
"-K2222222222" : {
"question" : "Should Britian leave the EU?",
"options" : {
"1" : "answer 1",
"2" : "answer 2",
"3" : "answer 3"
},
}
}
}
but I can't figure out how to add methods in the MultipleChoice class. And ideas how to get the effect of an array so I can retrieve options[0] etc. or options/"1"?
Upvotes: 1
Views: 945
Reputation: 7720
An array starts from index 0, so your database structure should be
{
"multiple_choice" : {
"-K2222222222" : {
"question" : "Should Britian leave the EU?",
"options" : {
"0" : "answer 1",
"1" : "answer 2",
"2" : "answer 3"
}
}
}
}
And the model class for each multiple_choice
public class MultipleChoice {
private String id;
private String question;
private List<String> options;
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
... constructor and other getter setter...
}
This is an example of how to retrieve each option from the list
MultipleChoice multipleChoice = dataSnapshot.getValue(MultipleChoice.class);
String firstOption = multipleChoice.getOptions().get(0);
String secondOption = multipleChoice.getOptions().get(1);
String thirdOption = multipleChoice.getOptions().get(2);
Hope this helps :)
Upvotes: 2
Reputation: 5256
You can use Map:
private Map<String, String> options;
how to get all child list from Firebase android
Upvotes: 1