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()));
}
Related
I tried to parse this JSON address but failed. The code I tried is failing, no data is reflected. Can you help me?
My Code;
private void parseJSON() {
final String url = "json website";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(null);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String imageref = hit.getString(null);
mExampleList.add(new ExampleItemRef(imageref));
}
This JSON;
[
"https://www.asdasd.com/images/r/a.png",
"https://www.asdasd.com/images/r/b.png",
"https://www.asdasd.com/images/r/c.png",
"https://www.asdasd.com/images/r/d.png",
"https://www.asdasd.com/images/r/e.png"
]
Just remove all unnecessary part from your code and change it like below. You need to put your json string when creating array
private void parseJSON() {
final String url = "json website";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
mExampleList.add(new ExampleItemRef(jsonArray.getString(i)));
}
}
You could do like this:
ArrayList < ExampleItemRef > mExampleList = new ArrayList <ExampleItemRef > ();
String jsonStr =
"[ \"https://www.asdasd.com/images/r/a.png\", \"https://www.asdasd.com/images/r/b.png\", \"https://www.asdasd.com/images/r/c.png\", \"https://www.asdasd.com/images/r/d.png\", \"https://www.asdasd.com/images/r/e.png\" ]";
try {
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
String imageref = jsonArray.getString(i);
mExampleList.add(new ExampleItemRef(imageref));
}
} catch (JSONException e) {
e.printStackTrace();
}
codes are self explanatory, so no comments,hope helpful
Edited: try this:
private void parseJSON() {
final String url = "json website";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
String imageref = jsonArray.getString(i);
mExampleList.add(new ExampleItemRef(imageref));
}
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);
}
}
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 am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray
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();
}
}