this is my request code ,please help me to parse it correctly. I want all the options for each particular question but I am getting only one option .can anyone solve it. I have attached SS of my data format.
JsonObjectRequest request = new JsonObjectRequest(
"http://www.proprofs.com/quiz-school/mobileData/request.php?request=QuizStart&module=handShake&title=does-your-crush-like-you-girls-only_1",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// ArrayList<Data> listData = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONArray array = response.getJSONArray("quiz");
// JSONObject jsonObject = array.getJSONObject(0);
for (int i = 0; i < array.length(); i++) {
JSONObject currentArray = array.getJSONObject(i);
DataQuestions movie = new DataQuestions();
movie.setQuestion(currentArray.getString("question"));
String question = currentArray.getString("question");
System.out.println("question----------" + question);
movie.setQuesImage(currentArray.getString("QuesImage"));
String image = currentArray.getString("QuesImage");
System.out.println("QuesImage----------" + image);
JSONArray keys= currentArray.getJSONArray("keys");
for(int j =0;j<keys.length();j++){
JSONObject keyobject = keys.getJSONObject(j);
movie.setOption(keyobject.getString("option"));}
/*String key = null;
if(keys.getJSONObject("option")) {
key = keys.getString("option");
}
movie.setOption(key);*/
/* JSONArray jsonArray1 = (jsonObject.getJSONArray("keys"));
int numberOfItemsInResp = jsonArray1.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
DataQuestions options = new DataQuestions();
// movie = new DataQuestions();
options.setOption(jsonObject2.getString("option"));
String optios = jsonObject2.getString("option");
System.out.println("option----------" + options);
// JSONArray jsonArray1 = (response.getJSONArray("keys"));*/
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
Toast.makeText(MainActivity.this, "No Items Available", Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request);
}
This is because, you use a single object in second for loop. You should to define keys object and stored within arraylist in main object. Like this
public class Quiz {
String quizId;
String QuesImage;
String question;
String questionId;
String Type;
int index;
ArrayList<Keys> keysList;
}
public class Keys{
String answerId;
String option;
String AnsImage;
}
and parse it
JSONArray array = response.getJSONArray("quiz");
for (int i = 0; i < array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
Quiz quiz = new Quiz();
quiz.QuesImage = jsonObj.getString("QuesImage");
quiz.question = jsonObj.getString("question");
quiz.questionId = jsonObj.getString("questionId");
quiz.Type = jsonObj.getString("Type");
quiz.index = jsonObj.getInt("index");
JSONArray keys = jsonObj.getJSONArray("keys");
for (int j = 0; j < keys.length(); j++) {
JSONObject keysObj = keys.getJSONObject(j);
Keys keys = new Keys();
keys.answerId = keysObj.getString("answerId");
keys.option = keysObj.getString("option");
keys.AnsImage = keysObj.getString("AnsImage");
quiz.keysList.add(keys);
}
}
Related
private void loadCricketPlayer() {
//getting the progressbar
final ProgressBar cricketProgressBar = findViewById(R.id.cricketProgressBar);
//making the progressbar visible
cricketProgressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_new,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cricketProgressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("squad");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
JSONArray bArray = obj.getJSONArray("players");
for (int j = 0; j < bArray.length(); j++){
JSONObject jsonObject1 = bArray.getJSONObject(j);
cricket_Player_POJO cricketPlayer = new cricket_Player_POJO(jsonObject1.getString("name"));
cricketListItem.add(cricketPlayer);
}
}
cricket_Player_List cricketList = new cricket_Player_List(cricketListItem, getApplicationContext());
cricketPLayerlistView.setAdapter(cricketList);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json Array data for fetching the data from the server
This is my JSONARRAY example. For fetching the data:
{
"squad": [
{
"name": "Australia",
"players": [
{
"pid": 7252,
"name": "Tim Paine"
},
{
"pid": 489889,
"name": "Pat Cummins"
},
{
"pid": 5334,
"name": "Aaron Finch"
},
]
}]
}
How can I Fetch this code Help me How can I do it I am using volley for this and I want to fetch this data in the listview android
How can I Fetch this code Help me How can I do it I am using volley for this and I want to fetch this data in the listview android
replace with this code
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
JSONArray jArray = obj.getJSONArray("squad");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
JSONArray bArray = jsonObject.getJSONArray("players");
for (int j = 0; j < bArray.length(); j++){
JSONObject jsonObject1 = bArray.getJSONObject(j);
cricket_Player_POJO cricketPlayer = new cricket_Player_POJO(jsonObject1.getString("name"));
cricketListItem.add(cricketPlayer);
}
}
cricket_Player_List cricketList = new cricket_Player_List(cricketListItem, getApplicationContext());
cricketPLayerlistView.setAdapter(cricketList);
} catch (JSONException e) {
e.printStackTrace();
}
I can parse json from an url in this way:
String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
String url = link1;
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I want to parse my json from multiple url.
I want to parse url1 and url2 at the same time.
How can I do that?
Why don't you use "links" as array ?
In case you will use an array:
JSONObject jsonObject = new JSONObject();
JSONArray keys = jsonObject.getJSONArray("links");
int length = keys.length();
for (int i = 0; i < length; i++) {
new ReadJSON().execute(keys.getString(i));
}
Anyway, you take all the keys and go one after the other, and then query each
EDIT:
JSONObject jsonObject = new JSONObject(/*Your links json*/);
JSONObject links = jsonObject.get("links");
Iterator<String> keys = links.keys();
while (keys.hasNext()) {
new ReadJSON().execute(links.getString(keys.next()));
}
This is my array which I retrieve from a url
[{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00
00:00:00","last_updated":"2016-08-29 07:52:35"}]
I have array without array name, I can read data if there is name of jason array but I am unable to do that with this type of array.
any suggestion my code for json with array name
String json = serviceClient.makeServiceCall(URL_ITEMS, ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture resps", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
Double matchId = Double.parseDouble(c.getString(TAG_MATCHID));
Log.d("matchId", String.valueOf(matchId));
Double teamA = Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);`
List<Double> listMatch = new ArrayList<Double>();
List<Double> listA = new ArrayList<Double>();
List<String> listB = new ArrayList<String>();
Create three arrayList and add data in that list
if(json!=null)
{
try {
Log.d("try", "in the try");
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
listMatch.add(Double.parseDouble(c.getString(TAG_MATCHID)));
Log.d("matchId", String.valueOf(matchId));
listA.add(Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
listB.add(c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
directly pass jsonarray string to JSONArray object constructor.
String json = [{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00 00:00:00","last_updated":"2016-08-29 07:52:35"}];
JSONArray array = new JSONArray(json);
You can directly pass the JSON response from the URL to the json if it is dynamic. Use something like this:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("ash_id");
String code = jsonobject.getString("ash_code");
String name = jsonobject.getString("ash_name");
String cell = jsonobject.getString("ash_cell");
String nic = jsonobject.getString("ash_nic");
String lng = jsonobject.getString("ash_long");
String lat = jsonobject.getString("ash_lat");
String zm_id = jsonobject.getString("zm_id");
String created_by = jsonobject.getString("created_by");
String created_date = jsonobject.getString("created_date");
String updated_date = jsonobject.getString("last_updated");
}
This will update your data, as long as the node names remain the same.
That's all :)
This code worked for me:
public class MainActivity extends AppCompatActivity {
private TextView textView;
private RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
queue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
String url = "http://10.216.70.19:8080/restServices/webapi/services/getAGVStatusList"; //This is my Json url
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//weatherData.setText("Response is :- ");
parseData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Data Not Received");
}
});
queue.add(request);
super.onStart();
}
private void parseData(String response) {
try {
// Create JSOn Object
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
textView.setText(jsonObject.getString("batteryLevel")); //get the desired information from the Json object
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I Have a Remote Database that contains 6 rows.
Here's my code, I put it in List so that i can get the size,
But it's always returning 0.
public List<Comments> getComments() {
final List<Comments> commentsData = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
return commentsData;
}
I need the size for some use.
Why is it always returning zero?
I even tried adding a counter++ inside for loop.
But when i get the value of the counter its still zero.
JsonObjectRequest run on a background thread. That's why you getting the list size 0. you must work into the public void onResponse(JSONObject response) {} function .
Exmp.
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
// **you may call function and pass the list value to update your ui component. you will get the real size of list here.**
} catch (JSONException e) {
e.printStackTrace();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Probably a stupid question. I'm getting a JSONArray in the form of
[{'route':'route1'}, {'route':'route2'}, {'route':'route3'}]
I want to get it into a String array of
["route1", "route2", "route3"]
How?
The solution that comes to my mind would be to iterate through and just grab the values
String[] stringArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringArray[i]= jsonArray.getJSONObject(i).getString("route");
}
Try this
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(responseString);
if (jsonArray != null) {
String[] strArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
strArray[i] = jsonArray.getJSONObject(i).getString("route");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Followed by this TUTORIAL
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(i = 0; i < arr.length; i++){
list.add(arr.getJSONObject(i).getString("name"));
}
Or use GSON
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
//(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]
//(Deserialization)
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
//ints2 is same as ints
You can try below solutions,
Just replace { and } by following code
String jsonString = jsonArray.toString();
jsonString.replace("},{", " ,");
String[]array = jsonString.split(" ");
Or
JSONArray arr = new JSONArray(yourJSONresponse);
List<String> list = new ArrayList<String>();
for(i = 0; i < arr.length; i++){
list.add(arr.getJSONObject(i).getString("name"));
}
this will convert to Arraylist and then if you want it to string then convert it to StringArray. for more reference use this link
as straight forward as it can be
List<String> list = new ArrayList<String>();
for( int ix = 0; ix < yourArray.length(); ix++ ){
list.add( yourArray.getJSONObject( ix ).getString( "route" ) );
}
return list.toArray( new String[] );
// try this way here i gave with demo code
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("route","route1");
jsonArray.put(jsonObject1);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("route","route2");
jsonArray.put(jsonObject2);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("route","route3");
jsonArray.put(jsonObject3);
String[] array = jsonArrayToArray(jsonArray);
for (int i=0;i<array.length;i++){
Log.i((i+1)+" Route : ",array[i]);
}
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public String jsonToStrings(JSONObject object) throws JSONException {
String data ="";
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
data+=fromJson(object.get(key)).toString()+",";
}
return data;
}
private Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return jsonToStrings((JSONObject) json);
} else if (json instanceof JSONArray) {
return jsonArrayToArray((JSONArray) json);
} else {
return json;
}
}
private String[] jsonArrayToArray(JSONArray array) throws JSONException {
ArrayList<Object> list = new ArrayList<Object>();
int size = array.length();
for (int i = 0; i < size; i++) {
list.add(fromJson(array.get(i)));
}
ArrayList<String> arrayList = new ArrayList<String>();
for (int i=0;i<list.size();i++){
String[] row = ((String)((String)list.get(i)).subSequence(0,((String)list.get(i)).length()-1)).split(",");
for (int j=0;j<row.length;j++){
arrayList.add(row[j]);
}
}
String[] strings = new String[arrayList.size()];
for (int k=0;k<strings.length;k++){
strings[k]=arrayList.get(k);
}
return strings;
}
}