How to get JSON data out of JSON Array? - android

I am using the Volley libary to understand working with JSON data, i have successfully retrieved some data and would like to know how to get the individual data out of my json array? I have tried doing what user's suggested on previous stackover flow post but only the json array data is showing up
#Override
public void downloadJson() {
final String url = "https://dog.ceo/api/breeds/image/random/2";
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("message");
Log.i("jsonArray", jsonArray.toString());
for(int i=0; i>jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
Log.i("obj", object.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(getRequest);
}

exactly i can't understand your question .
but in your code there are some problem .
in below you can see my proposal code .
for(int i=0; i<jsonArray.length(); i++)
{
Log.i("obj", jsonArray.get(i).toString());
}
in this code you can get each data from you'r JSONArray and use that URL to load image.
if this is not answer to you'r question i will be glad if you give some explanation about you'r question.

There is mistake in your for loop,
for(int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
Log.i("obj", object.toString());
}
Hope it will help!!

Related

Two Json lists in one spinner using else statement

In my app I have 2 spinners they are populated with JSON data pulled from a file on my company server.
The spinners are populated if a correct email, password and clientID is entered.
Now I want to add that if the details are wrong or non exist they must show a different JSON.
I am trying to do this by calling an else if statement in my onResponse method.
To summarize
I want each spinner to show a JSON data array with categories/client details in if the login information is entered/correct (this works but I was asked to add this second array for errors) and if there is missing/incorrect information it must show the the JSON array with the errors in. Both JSON arrays are in the same file.
I believe my problem lies with my adapter, as it is calling one ArrayList is it possible to let it call both array lists heres the adapter, I want to add a second ArrayList to this, the current one is "CategoryName"
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
CODE FOR LOADING THE SPINNERS DATA
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String category=jsonObject1.getString("Category");
CategoryName.add(category);
}
}
if (jsonObject.getInt("failed") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("errors");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String error=jsonObject1.getString("reason");
Errors.add(error);
}
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
You simply have to use your Errors ArrayList. Currently you add the information to it (in your second if branch) but never put it into the spinner.
Try this:
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String category=jsonObject1.getString("Category");
CategoryName.add(category);
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
}
if (jsonObject.getInt("failed") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("errors");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String error=jsonObject1.getString("reason");
Errors.add(error);
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, Errors));
}

Android Studio: How to parse a JSON Object from Inside of a JSON Array?

I am trying to parse the following JSON data into a recycler view. In particular, I want to parse the address object to display the locationName, line1, city, state and zip, but I cant get the parsing method right.
{
"pollingLocations": [
{
"address": {
"locationName": "LITTLE LEAGUE HEADQUARTERS",
"line1": "6707 LITTLE LEAGUE DR",
"city": "SAN BERNARDINO",
"state": "CA",
"zip": "92407"
},
"notes": "",
"pollingHours": "07:00-20:00",
"sources": [
{
"name": "Voting Information Project",
"official": true
}
]
}
]
}
My issue is finding the address object. With the current code, I get a logcat error that says No value for locationName. I think this is because I first need to specify the address object to iterate through, but how do I do this? This is the current implementation that I have right now.
//fetch
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("pollingLocations");
for(int i = 0; i < array.length(); i++){
JSONObject addressObject = array.getJSONObject(i);
for (int x = 0; x < addressObject.length(); x++){
VotingLoc votingLoc = new VotingLoc(addressObject.getString("locationName"),
addressObject.getString("line1"),
addressObject.getString("city"),
addressObject.getString("state"),
addressObject.getString("zip"),
addressObject.getString("pollingHours"));
votingList.add(votingLoc);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Locat Error:
Is there an easier way of doing this? I believe the code for my rvadapter class and is correct and the error is in this method, but If you want to see any other code, let me know.
By getting first node in array you have obtained address node so no need to run loop there, address object is not an array you can get values directly. Try something like this:
JSONArray array = object.getJSONArray("pollingLocations");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String locationName = jsonObject.getJSONObject("address")
.getString("locationName");
Log.d("locationName", locationName);
JSONArray sourcesArray = jsonObject.getJSONArray("sources");
// run loop to get values from this array
for (int j = 0; j < sourcesArray.length(); j++){
JSONObject source = sourcesArray.getJSONObject(j);
String name = source.getString("name");
}
}
Another way could be using a json parser like gson (https://github.com/google/gson) or jackson (https://github.com/FasterXML/jackson). This may be a bit overhead if your only goal is to show these few values, as you must create some java classes, you may only need for parsing.

How to receive JSONArray

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

How can I get a JsonObject from a URL in Android?

I have to a JSONObject, especially the "data" content, in Android from a WebService, then I have to print it into a ListView or a Table.
This is my JSON:
{
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}
Let
response = {
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}
String status = response.get("status"); // status = 200
String status_message = response.get("status_message"); // status_message = "Direct ways found"
JSONArray message = response.getJSONArray("data");
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < message.length(); i++) {
HashMap<String, String> hm = new HashMap<String, String>();
JSONObject temp = message.getJSONObject(i);
hm.put("codice_linea",temp.getString("codice_linea"));
hm.put("partenza",temp.getString("partenza"));
hm.put("ora_partenza",temp.getString("ora_partenza"));
hm.put("arrivo",temp.getString("arrivo"));
....................................
.............................
aList.add(hm);
}
Finally all your JSON data is prased to List aList.
Then use custom Listview to show this data in Listview
Here is the full tutorial http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
Hope this solved your problem.
Try this
JSONObject jsonObject = new org.json.JSONObject(YourJsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
......
}
I assume you effort to get this Json in android , if i right try this:
Paste your example Json in Json Schema 2 Pojo , and site will generate Pojo classes
Convert your Json response to Pojo class with Gson
Add this line to your dependencies : compile 'com.google.code.gson:gson:2.4'
Convert Json result to Pojo :
Gson gson = new Gson();
YourPojo yourpojo= gson.fromJson(jsonresponse, YourPojo.class);
And handle result whatever you want .
If you didnt effort anything
Go to google and search how to handle Json in android or how to connect web service , for example you can search : HttpUrlConnection , OkHttp, Retrofit ...
What you seem wanting to do is to re-create an existing JSONObject that is contained in an array.
If you use the JSONObject from the Android tools, you can use getJSONObject and getJSONArray.
According to the Documentation:
Returns the value mapped by name if it exists and is a JSONArray, or throws otherwise.
Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
See here for more details.
You have to do something like that:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Your-url-JsonObj, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
String status = response.getString("status");
String status_message = response.getString("status_message");
JSONArray jsonArray =jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
jsonArray.getJSONObject(i).getString("arrivo");
jsonArray.getJSONObject(i).getString("ora_arrivo");}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}

storing json parsed values as string in array

I've got a json object, which is being collected into a function as string.
It contains array
{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P.
REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH
SINGH"}
and here is the android code
public void func4(View view)throws Exception
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc5.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try {
/* here I need output in an array,
and only names not the "officer_name" */
} catch (Exception e) {
tx.setText((CharSequence) e);
}
//tx.setText(User_List.get(1));
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
The output I've shown above is in String, need to get it in array. Please help!
If the output you got is something like this.
String outputJson=[{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P. REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH SINGH"}]
Then its a JSON Array.
You can parse it as
JsonArray array=new JsonArray(outputJson);
Then loop this json array using
for(JsonObject jsonObj in array){
String officerName=[jsonObj getString("officer_name");
}
You can use something like above The mentioned code is not correct syntactically but yes conceptually correct. You can go ahead with this.
List < String > ls = new ArrayList< String >();
JSONArray array = new JSONArray( response );
for (int i = 0; i < array.length() ; i++ ) {
JSONObject obj = array.getJSONObject(Integer.toString(i));
ls.add(obj.getString("officer_name"));
}
This would work
try {
JSONArray array= new JSONArray(response);
//array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
//JSONObject obj = response.getJSONArray(i);
JSONObject jsonLineItem = (JSONObject) array.getJSONObject(i);
String name_fd = jsonLineItem.getString("officer_name");
User_List.add(jsonLineItem.getString("officer_name"));
Log.d("JSONArray", name_fd+" " +name_fd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tx.setText( e.toString());
}

Categories

Resources