如何从json数组中读取数据并将其从一个片段传递到另一个片段并在recyclerview中显示?

时间:2016-10-28 08:00:08

标签: android json android-recyclerview

它是测验的数据,其中包括“id”作为问题ID,“test_id”作为测验ID。我需要获取所有问题(问题的编号可能不同)和选项以及正确的答案,并且需要在回收者视图中填充它。

[  
{  
"id":"13",
"test_id":"1",
"question":"find out relationship with the third word.",
"options":"[\"speed\",\"hiking\",\"needle\",\"direction\"]",
"correct_answer":"3",
"create_date":"2016-10-27 07:37:39",
"update_date":null
},
{  
"id":"14",
"test_id":"1",
"question":"find out which of the answer choices completes the same relationship with the third word.",
"options":"[\"not\",\"set\",\"get\",\"pet\"]",
"correct_answer":"3",
"create_date":"2016-10-28 07:37:39",
"update_date":null
},
{  
"id":"15",
"test_id":"1",
"question":"the same relationship with the third word.",
"options":"[\"jet\",\"read\",\"nor\",\"sour\"]",
"correct_answer":"3",
"create_date":"2016-10-28 10:37:39",
"update_date":null
},
{  
"id":"16",
"test_id":"1",
"question":"A good way to figure out the relationship ",
"options":"[\"trekking\",\"hiking\",\"seed\",\"turn\"]",
"correct_answer":"3",
"create_date":"2016-10-28 18:37:39",
"update_date":null
}
]

我使用过这段代码:

String res = new QuestionRequest(getActivity().getApplicationContext(), "level_question").execute(test_id).get();

JSONArray result = new JSONArray(res);

List<DataQuestion> data=new ArrayList<>();


for(int i=0;i<result.length();i++){
                    JSONObject json_data = result.getJSONObject(i);
                    DataQuestion rowdata = new DataQuestion();
                    rowdata.id= json_data.getString("id");
                    rowdata.test_id= json_data.getString("test_id");
                    rowdata.question= json_data.getString("question");
                    rowdata.answer_choices= json_data.getString("answer_choices");
                    rowdata.correct_answer= json_data.getString("correct_answer");
                    data.add(rowdata);
                }

我把它存放在arraylist中。现在应该如何发送另一个片段。我尝试使用Bundle发送数据,但不知道如何发送arraylist。

其中: DataQuestion.java是

public class DataQuestion {
public String id;
public String test_id;
public String question;
public String answer_choices;
public String correct_answer;
}

3 个答案:

答案 0 :(得分:0)

我建议您使用库Retrofit(https://square.github.io/retrofit/)来调用API请求并序列化响应。在您的情况下,您将创建一个包含许多字段的类(id,test_id,question,options,...)。

然后为Recyclerview创建一个接受模型类的适配器。最后,您可以使用cardview显示您的项目。

答案 1 :(得分:0)

如果你发布你试图解析这个json的东西,它会更好。解析json在android中很容易,你只需要从你拥有的数据创建一个JSONArray或JSONObject。在你的情况下它是一个JSONArray。

稍后您可以创建包含json数据的模型,您可以将模型传递给适配器,并将该适配器传递给recyclerview或list。

答案 2 :(得分:0)

您可以使用Volley获取数据并创建JSONObject以将Response解析为问题列表(使用模型),然后将该列表传递给适配器,您可以在RecyclerView / ListView中的列表项中设置问题。

相关问题