How to receive JSONArray - android

Following guide I see this:
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("nome_stanza"));
movie.setThumbnailUrl(obj.getString("icona"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController2.getInstance().addToRequestQueue(movieReq); //i need this movieReq
But I don't have a URL where the Jsoncode is collocated, I receive jsoncode from another method that gives me a string like this:
{"risposta_server": [{"nome_stanza":"via oslavia"},{"icona":"http:\/\/****.**.**.**\/fil***\/****\/images\/icon\/icon2.png"},{"Admin":"s"}]}
Then, how can I change the first code to use this result?

I've got mixed up in response, but I understand it's supposed to come Json Object.The next step:
JSONOArray array = response.getJSONArrary("risposta_server");
for (int i = 0; i < array.length(); i++) {
try {
JSONObject obj = array.getJSONObject(i);
Movie movie = new Movie();
if(i == 0){
movie.setTitle(obj.getString("nome_stanza"));
}else if(i == 1){
movie.setThumbnailUrl(obj.getString("icona"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
...
See the job if I misunderstand.

Maybe you need json encode like json_encode($str) on php script. Where $str is an array list.
So, your server script will be like this
$arr = array('hello', 'world', 'where', 'i', 'life');
echo json_encode($arr);
Then you will get json data from server

Related

how to add all values of JSONObject to JSONArray

First, I want to add all ArrayList Values into JsonObject then I want to add these JSON object to JsonArray I have done wright in the first I have added all ArrayList to JsonObject but I can't add all JsonObject to JsonArray.
This is my code to convert json object to json Array:-
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
for (int i = 0; i < records.size(); i++) {
try {
jsonObject.put("sid", records.get(i).getsid());
jsonObject.put("name", records.get(i).getpName());
jsonArray.put(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("ATTENDANCE", jsonArray.toString() + "");
}
});
I am getting only the last value of the ArrayList please help me I want The output to be like these
[
{
"student_no":"3924/08",
"firstname":"olana
},
{
"student_no":"4011/08",
"firstname":"yallem"
}
]
That is because you're creating only one object and putting it inside the for loop and you have to create new objects for every iteration.
Put your
JSONObject jsonObject = new JSONObject();
inside your for loop
like this
for (int i = 0; i < records.size(); i++) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sid", records.get(i).getsid());
jsonObject.put("name", records.get(i).getpName());
jsonArray.put(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < records.size(); i++) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sid", records.get(i).getsid());
jsonObject.put("name", records.get(i).getpName());
jsonArray.put(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("ATTENDANCE", jsonArray.toString() + "");
}
});

Android parse json from multiple url

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()));
}

Android Volley: using a for loop to extract data from a JsonObject

I am working on an android project that will get a Json array from a server and then I want to iterate through the array and extract data from each Json object in the array. When I run this code the textviews do not change, but if I remove the for loop and everything in it, and then uncomment the two lines below the for loop, things seems to work. How can you iterate through the Json objects in the array so that the info will be updated on the screen and change every second for each object in the array?
Thank you in advance!
name = (TextView)findViewById(R.id.nameTxt);
email = (TextView)findViewById(R.id.emailTxt);
serverButton = (Button)findViewById(R.id.getInfoBtn);
serverButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(server_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject nameJson = response.getJSONObject(i);
name.setText(nameJson.getString("FirstName") + " " + nameJson.getString("LastName"));
email.setText(nameJson.getString("Email"));
Thread.sleep(1000);
}
//JSONObject nameJson = response.getJSONObject(1);
// name.setText(nameJson.getString("FirstName"));
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
name.setText("Something is wrong");
}
});
MySingleton.getInstance(MainActivity.this).addToRequestQueue(jsonArrayRequest);

How to access object>array>object>array>object in json?

I have to fetch text via json in url .
The hierarchy is given below :
object>array>object>array>object.
I want to get text with this code .But I am getting error :org.json.JSONException: No value for text
Below is the code :-
public class ListViewActivity extends Activity {
// Log tag
private static final String TAG = ListViewActivity.class.getSimpleName();
// change here url of server api
private static final String url = "http://2e9b8f52.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
intent.putExtra("name", movie.getName());
intent.putExtra("average_ratings", movie.getAverage_ratings());
intent.putExtra("full_address", movie.getAddress());
intent.putExtra("image_url", movie.getThumbnailUrl());
intent.putExtra("cuisine",movie.getCuisine());
intent.putExtra("cost",movie.getCost());
startActivity(intent);
}
});
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Please Keep patience.Its loading...");
pDialog.show();
// Creating volley request obj
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray
restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
//movie.setThumbnailUrl(obj.getString("image"));
movie.setThumbnailUrl(obj.getString("org_image_url"));
movie.setAverage_ratings(obj.getString("average_ratings"));
movie.setCuisine(obj.getString("cuisine"));
movie.setAddress(obj.getJSONObject("address").getString("area"));
// movie.setAddress(obj.getJSONObject("address").getString("full_address"));
movie.setCost(obj.getString("cost"));
movie.setDistance( obj.getDouble("distance"));
movie.settext(obj.getString("text"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
I am attaching snapshot of json data. In the snapshot we can see the color "Text=15% discount on bill " i have to access .
try {
String yourresponseString ="";// this string refer to your api response
JSONObject jsonObject = new JSONObject(yourresponseString);
JSONArray objJsonArray = new JSONArray(jsonObject.getString("restaurants"));
for (int i = 0; i < objJsonArray.length(); i++) {
JSONArray objInnerJsonArray = objJsonArray.getJSONObject(i).getJSONArray("restaurant_offers");
for (int j = 0; j < objInnerJsonArray.length(); j++) {
//Here you can acess youe bill discount value
JSONObject objInnerJSONObject = objInnerJsonArray.getJSONObject(j);
System.out.println("Discount==>" + objInnerJSONObject.getString("text"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You can parse like this.And using this classes you can parse any type of hierarchy.
JSONArray restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
JSONArray textJSONArray= obj.getJSONArray("restaurant_offers");
for (int j = 0; j < textJSONArray.length(); j++) {
JSONObject txtobj =textJSONArray.getJSONObject(i);
movie.settext(txtobj .getString("text"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
try this code restaurant_offers is a JSONArray so you can parse like this
You can parse like this
JSONObject apiResponseJsonObject= // Your API Response
try {
JSONArray restaurantJSONArray = apiResponseJsonObject.getJSONArray("restaurants");
// you can get any text from an object like this
restaurantJSONArray.getJSONObject(index).getString("name");
restaurantJSONArray.getJSONObject(index).getString("cost"); // Like this
//If you want to access phone numbers of specific object
JSONArray phoneJSONArray=restaurantJSONArray.getJSONObject(index).getJSONArray("phone_numbers");
// And you can get specific data from phoneNumber like this
phoneJSONArray.getJSONObject(phoneNumberIndex).getString("number");
//TO get Address, you can use like this
JSONObject addressJSONObject=restaurantJSONArray.getJSONObject(index).getJSONObject("address");
//Like this you can parse whatever you want.
} catch (JSONException e) {
e.printStackTrace();
}
You must change the for loop content like this
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
JSONArray restauranstOffersJSONArray = obj.getJSONArray("restaurants_offers");
for (int i = 0; i < restauranstOffersJSONArray.length(); i++) {
JSONObject offersObj = restauranstOffersJSONArray.get(i);
String text = offersObj.getString("text");
}

why I am having double brackets in json

why I am having double '[[' ?
should it be one bracket ? '['
[[{"name":"50 shade of
gray","path":"http://api.androidhive.info/json/movies/1.jpg","description":"long
story","likes":"5","comments":" Very
nice"},{"name":"Transformers","path":"http://api.androidhive.info/json/movies/2jpg","description":"Robots","likes":"7","comments":"
beautiful"},{"name":"Avangeers","path":"http://api.androidhive.info/json/movies/3.jpg","description":"hulk
and iron man","likes":"8","comments":" wow"}]]
this is my php
$sql = "select name , path , description , likes , comments from image ";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('name'=>$row[0],
'path'=>$row[1],
'description'=>$row[2],
'likes'=>$row[3],
'comments'=>$row[4]
));
}
echo json_encode(array($result));
mysqli_close($con);
And is it correct getting it in such code ?
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("r", response.toString());
hidePDialog();
System.out.print(response);
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("path"));
movie.setRating(obj.getString("description"));
// movie.setRating(((Number) obj.get("description"))
// .doubleValue());
movie.setYear(obj.getString("likes"));
// movie.setYear(obj.getInt("likes"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("comments");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.print(error);
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
$result is an array.
You push associative arrays (that become objects) in that array, so now you have [{...},{...}]
Then you do:
echo json_encode(array($result));
so you get an array with an array in it, resulting in the above result with extra '[' around: [[{...},{...}]]

Categories

Resources