2017-01-19 56 views
1

我正在编写一个使用Firebase for cloud数据库的Android应用程序。它基本上是一个多选调查问题的应用程序进口到火力地堡我Android Firebase阵列

{ 
    "multiple_choice" : { 
    "-K2222222222" : { 
     "question" : "Question text", 
     "opt1" : "answer 1", 
     "opt2" : "answer 2", 
     "opt3" : "answer 3" 
    } 
    } 
} 

我添加了一个选择题类,像这样

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; 
    } 

} 

,让我找回使用火力地堡引用主类这一数据。

现在我想让它看起来像一个选项数组,虽然FB并不是按照这种方式工作,所以它可以使用任意数量的选项而不是固定的3或任何其他选项。这个json文件加载到FB

{ 
     "multiple_choice" : { 
     "-K2222222222" : { 
      "question" : "Should Britian leave the EU?", 
      "options" : { 
      "1" : "answer 1", 
      "2" : "answer 2", 
      "3" : "answer 3" 
      }, 
     } 
     } 
    } 

但我无法弄清楚如何在MultipleChoice类中添加方法。和想法如何获得数组的效果,所以我可以检索选项[0]等或选项/“1”?

回答

2

数组索引0开始,所以你的数据库结构应该是

{ 
    "multiple_choice" : { 
     "-K2222222222" : { 
      "question" : "Should Britian leave the EU?", 
      "options" : { 
       "0" : "answer 1", 
       "1" : "answer 2", 
       "2" : "answer 3" 
      } 
     } 
    } 
} 

和每个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... 
} 

这是如何从列表中检索每个选项

MultipleChoice multipleChoice = dataSnapshot.getValue(MultipleChoice.class); 
String firstOption = multipleChoice.getOptions().get(0); 
String secondOption = multipleChoice.getOptions().get(1); 
String thirdOption = multipleChoice.getOptions().get(2); 

希望这有助于:)

+0

优秀的IT工作的感谢一个例子! – tagliatelli

+0

真棒,请接受我的回答:) – Wilik