Я пытаюсь получить данные JSON с сервера в приложении для Android. Файл JSON состоит из 4 вопросов. Я пытаюсь получить вопрос и 4 варианта по отдельности и настроить просмотр списка в Android, чтобы отображать как вопрос с несколькими вариантами выбора. Android прошел ответ, но я не смог получить отдельные данные. Ниже мой код.
file.json
{"multiple":[{
"question": "In which course are you inrolled in?",
"choice 1":"BIM",
"choice 2":"BBA",
"choice 3":"BIT",
"choice 4":"BSCCSIT"
},
{
"question": "What comes after n?",
"choice 1":"s",
"choice 2":"t",
"choice 3":"o",
"choice 4":"p"
}
]
}
sending.php
<?php
header('Content-type:application/json');
$data =file_get_contents('/var/www/html/file.json');
$row =json_encode($data);
echo ($row);
?>
MainActivity.java
package com.multiple;
import android.app.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity
{
private ListView listview;
List<HashMap<String,String>> collect= new ArrayList<HashMap<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.list);
populate p = new populate();
p.execute();
}
public class populate extends AsyncTask<Void, Void, Void>
{
public Void doInBackground(Void... params)
{
try
{
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet("http://192.168.10.120/sending.php");
HttpResponse res= client.execute(post);
HttpEntity entity = res.getEntity();
String response = EntityUtils.toString(entity);
Log.i("response",response);
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.optJSONArray("multiple");
for(int i=0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.optString("question").toString();
String name = jsonObject.optString("choice1").toString();
String salary =jsonObject.optString("choice2").toString();
String ssalary =jsonObject.optString("choice3").toString();
String sssalary =jsonObject.optString("choice4").toString();
Log.i("qq",id);
Log.i("asdfas",salary);
Log.i("asjdfha",name);
Log.i("asdfas",salary);
}
// String questions = obj.optString("question").toString();
// String choices=obj.optString("answers").toString();
}
catch(IOException ex){}
catch(JSONException ex){}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
}
String[] str = new String[]{"first","second","third","fourth","fifth"};
int[] val = new int[]{R.id.textView1,R.id.checkBox1,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4};
}
Как я могу получить данные JSON отдельно? /
Вам необходимо сохранить значения в Collection
, ArrayList
JSONObject
будет JSONObject
в этой ситуации:
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
arrListJsonObject.add(jsonObject);
/* String id = jsonObject.optString("question").toString();
String name = jsonObject.optString("choice1").toString();
String salary =jsonObject.optString("choice2").toString();
String ssalary =jsonObject.optString("choice3").toString();
String sssalary =jsonObject.optString("choice4").toString();
Log.i("qq",id);
Log.i("asdfas",salary);
Log.i("asjdfha",name);
Log.i("asdfas",salary); */
}
Здесь arrListJsonObject - это ArrayList<JSONObject>
. Теперь вы можете использовать:
for(int i=0;i<arrListJsonObject.size();i++){
JSONObject jsonObject = arrListJsonObject.get(i); // or arrListJsonObject.get(position) inside getView method of a custom Adapter.
String question = jsonObject.optString("question").toString();
String c1 = jsonObject.optString("choice1").toString();
String c2 = jsonObject.optString("choice2").toString();
String c3 = jsonObject.optString("choice3").toString();
String c4 = jsonObject.optString("choice4").toString();
// Now you have question and choices as question, c1, c2, c3, c4 respectively.
}
Надеюсь, это поможет!!!
printStackTrace()
в блоке catch?
используйте ArrayList>()
ArrayList<HashMap<String,String>> arr_list=new ArrayList<HashMap<String,String>>();
arr_list.clear(); // создаем и очищаем массив
а также
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.optJSONArray("multiple");
int count=1;
for(int i=0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id=String.valueOf(count);
String ques = jsonObject.optString("question").toString();
String c1= jsonObject.optString("choice1").toString();
String c2=jsonObject.optString("choice2").toString();
String c3=jsonObject.optString("choice3").toString();
String c4=jsonObject.optString("choice4").toString();
addToArray(id,ques,c1,c2,c3,c4);
count++;
}
тогда..
{
здесь ваше содержание}
Strings
в вашlistview
и отобразите с помощьюArrayAdapter