如果您不需要执行复杂的查询,我建议您将数据存储在
json中,因为它可以很好地与Android应用程序集成,使用像
GSON或
Jackson这样的库。
如果您不想在每次问题更改时重新构建应用程序/重新部署,请考虑拥有一个小型Web服务器(如apache,nginx,tomcat),该服务器提供您在应用程序加载时请求的JSON文件。因此,您将在应用程序在线时下载问题或使用缓存的问题。
XML是一种冗长的格式,对于这种用途没有太多功能......
为了回答您的最后一个问题,您可以像这样组织您的代码:
public class SOF_37078005 {
@Test
public void test() {
QuestionsBean questions = new QuestionsBean();
QuestionBean b=buildQuestionExemple();
questions.add(b);
questions.add(b);
System.out.println(questions.toJson());
}
private QuestionBean buildQuestionExemple() {
QuestionBean b= new QuestionBean();
b.title="What is the size of your boat?";
b.pictures.add("/res/images/boatSize.jpg");
b.order= 1;
return b;
}
public class QuestionsBean{
private List<QuestionBean> list = new ArrayList<QuestionBean>();
public QuestionsBean add(QuestionBean b ){
if(b!=null && b.title!=null){
for(QuestionBean i : list){
if(i.title.compareToIgnoreCase(b.title)==0){
System.out.println("Question "+b.title+" already exists - skipped & not added");
return this;
}
}
System.out.println("Question "+b.title+" added");
list.add(b);
}
else{
System.out.println("Question was null / not added");
}
return this;
}
public String toJson() {
ObjectMapper m = new ObjectMapper();
m.configure(Feature.ALLOW_SINGLE_QUOTES, true);
String j = null;
try {
j= m.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
System.out.println("JSON Format error:"+ e.getMessage());
}
return j;
}
}
public class QuestionBean{
private int order;
private String title;
private List<String> pictures= new ArrayList<String>();
private List<String> responseChoice = new ArrayList<String>();
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getPictures() {
return pictures;
}
public void setPictures(List<String> pictures) {
this.pictures = pictures;
}
public List<String> getResponseChoice() {
return responseChoice;
}
public void setResponseChoice(List<String> responseChoice) {
this.responseChoice = responseChoice;
}
}
}
控制台输出
Question What is the size of your boat? added
Question What is the size of your boat? already exists - skipped & not added
[{"order":1,"title":"What is the size of your boat?","pictures":["/res/images/boatSize.jpg"],"responseChoice":[]}]
GIST:提供了我为您制作的完整工作代码。
https://gist.github.com/jeorfevre/5d8cbf352784042c7a7b4975fc321466
总之,使用JSON的好方法是:
1)创建一个bean以构建您的json(请参见我的示例)
2)构建您的json并将其存储在文件中
3)使用Android从文件加载您的json到bean中(您已经有它在Android中)
4)使用bean来构建您的表单等(而不是json文本文件):D