I am new to Json. I want to retrieve the distance between two places using json. I want to get "text"(Distance b/w two places) from "distance" object which is in "legs" array which in turn is in "routes" array.
Link(http://maps.googleapis.com/maps/api/directions/json?origin=Adoor&destination=Thiruvananthapuram%20Zoo&sensor=false)
Java code:
String uri="http://maps.googleapis.com/maps/api/directions/json?origin="+destination+"&destination="+tour_place+"&sensor=false";
queue= Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.GET, uri, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array=response.getJSONArray("legs");
distances.add(array.getJSONObject(0).getJSONObject("distance").getDouble("text"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
}
});
queue.add(objectRequest);
Okay, will now post the code I did. Try this out.
try {
JSONObject json = new JSONObject(jStr);
JSONArray jaRoutes = json.getJSONArray("routes");
JSONArray jaLegs = jaRoutes.getJSONObject(0).getJSONArray("legs");
JSONObject joDistance = jaLegs.getJSONObject(0).getJSONObject("distance");
String text = joDistance.getString("text");
Toast.makeText(this, text, Toast.LENGTH_SHORT);
} catch (JSONException e) {
Log.d("SAMPLE", e.toString());
}
Let me know if it works.
Try this,
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
}
routes.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
Try code below:
try {
StringRequest sr = new StringRequest(Request.Method.GET, uri, (String) null, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
;
Log.d("", ".......response====" + response.toString());
////////
try {
JSONObject object = new JSONObject(response);
if (serverCode.equalsIgnoreCase("0")) {
}
if (serverCode.equalsIgnoreCase("1")) {
try {
if ("1".equals(serverCode))
{
JSONArray jsonArray = object.getJSONArray("routes");
if(jsonArray.length()>0)
{
for(int i=0; i<jsonArray.length(); i++)
{
JSONArray legs =jsonArray.getJSONArray("legs");
if(legs.length()>0)
{
for(int i=0; i<legs.length(); i++)
{
JSONObject object1 = legs.getJSONObject("distance");
String distance = object1.getString("text");
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
;
// VolleyLog.d("", "Error: " + error.getMessage());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(ForgotPasswordActivity.this, "Timeout Error",
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof ServerError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof NetworkError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
} else if (error instanceof ParseError) {
VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
}
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_email", email);
return params;
}
};
sr.setShouldCache(true);
sr.setRetryPolicy(new DefaultRetryPolicy(50000 * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(sr);
} catch (Exception e) {
e.printStackTrace();
}
Try this
try{
JSONObject object = new JSONObject(thewholething.toString());
JSONArray routes =object.getJSONArray("routes");
JSONArray legs=routes.getJSONObject(0).getJSONArray("legs")
JSONObject distance =legs.getJSONObject(0).getJSONObject("distance");
String text=distance.getString("text");
}
catch (JSONException e) {
e.printStackTrace();
}
Now the String text contains your value.
From your response, you parse your routes array first.
JsonArray routes = response.getJsonArray("routes");
From here, you can get legs array like the following.
JsonArray legs = routes.getJsonArray("legs");
Related
My app supposedly to send a source and a destination as parameters to get the fastest bus route and then send them back as an array.
I want to make a list from a json array using volley. Here is an example of my array output.
{
"arrayrute":[
"Halte LIK",
"Halte Kampoeng Semarang",
"Halte Kaligawe 2",
"Halte Pasar Kobong",
"Halte Kota Lama"
]
}
How am I supposedly to make a list from it? Usually a json array from a database would have it's row name before the variable so I just have to use list.set_id(jsonobject.getString("id")) or list.set_id(jsonobject.optString("id"))
Here's my java code to get the array
private void getData() {
//Creating a string request
asal = spin_dari.getSelectedItem().toString().trim();
tujuan = spin_ke.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.GET, DIRECTION_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
results = j.getJSONArray("arrayrute");
//Calling method getStudents to get the students from the JSON Array
getdireksi(results);
//dirlist.add(results .toString());
} catch (JSONException e) {
e.printStackTrace();
}
adaptdir.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ASAL,asal);
params.put(KEY_TUJUAN,tujuan);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
dirlist.add(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Please Try with this way. Below is DEMO
String url = "{ \n" +
" \"arrayrute\":[ \n" +
" \"Halte LIK\",\n" +
" \"Halte Kampoeng Semarang\",\n" +
" \"Halte Kaligawe 2\",\n" +
" \"Halte Pasar Kobong\",\n" +
" \"Halte Kota Lama\"\n" +
" ]\n" +
"}";
try {
JSONObject jobject= new JSONObject(url);
JSONArray jarray=jobject.getJSONArray("arrayrute");
for(int k=0;k<jarray.length();k++)
{
String getValue=(jarray.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
Final
private void getdireksi(JSONArray j)
{
//Traversing through all the items in the json array
for(int k=0;k<j.length();k++)
try {
String getValue=(j.getString(k));
System.out.println("Intellij_Amiyo"+getValue);
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Your getdireksi() method is wrong. Put following code instead of yours.
private void getdireksi(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
String json = j.getString(i);
//Adding the name of the student to array list
dirlist.add(json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I was trying to add markers to a map automatically after getting the data from JSON, with the position that is in the api, this is what I have:
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh2 = new HttpHandler();
final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
if (jsonStrOportunidades != null) {
try {
JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String Designacao = jsonObject.getString("Designacao");
String Coord_LAT = jsonObject.getString("Coord_LAT");
String Coord_LONG = jsonObject.getString("Coord_LONG");
HashMap<String, String> oportunidades = new HashMap<>();
oportunidades.put("Designacao", Designacao);
oportunidades.put("Coord_LAT", Coord_LAT);
oportunidades.put("Coord_LONG", Coord_LONG);
double lat1 = Double.parseDouble(Coord_LAT);
double lng1 = Double.parseDouble(Coord_LONG);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
listaOportunidades.add(oportunidades);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
return null;
}
"mMap.addMarker" doesn't work, is it even possible creating markers from there?
Try setting the marker from onPostExecute. doInBackground isn't the place to update UI components.
#Override
protected String doInBackground(Void... params) {
HttpHandler sh2 = new HttpHandler();
final String jsonStrOportunidades = sh2.makeServiceCall(urlOportunidades);
Log.e(TAG, "Response from URL: " + jsonStrOportunidades);
return jsonStrOportunidades;
}
#Override
protected void onPostExecute(String jsonStrOportunidades){
if (jsonStrOportunidades != null) {
try {
JSONArray array = new JSONArray(jsonStrOportunidades);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String Designacao = jsonObject.getString("Designacao");
String Coord_LAT = jsonObject.getString("Coord_LAT");
String Coord_LONG = jsonObject.getString("Coord_LONG");
HashMap<String, String> oportunidades = new HashMap<>();
oportunidades.put("Designacao", Designacao);
oportunidades.put("Coord_LAT", Coord_LAT);
oportunidades.put("Coord_LONG", Coord_LONG);
double lat1 = Double.parseDouble(Coord_LAT);
double lng1 = Double.parseDouble(Coord_LONG);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat1, lng1)));
listaOportunidades.add(oportunidades);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Also, you need to change the AsyncTask class like this
YourAsyncTaskClass extends AsyncTask<String, Void, String>
I am parsing json value into gridView, but somehow its not showing any value in gridView, i am confused in json code as i think i am missing something in this code..kindly check :
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://........nList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONArray(response);
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
this is my json output:
{
"status_code": 200,
"status": "OK",
"status_message": "Success",
"pigeon_list": [
{
"id": "1",
"pigeon_name": "sofiee",
"auth_token": "58809c7129a5a",
"country_code": "AE",
"strain_id": "75",
"distance": "3",
"pigeon_price": "50.00",
"pigeon_details": "One of the best ",
"image": "http:.98a8ac5.jpeg",
"pedigree_image": "http://...1.jpeg",...
"status": "",
"created": "2017-01-19 16:52:14",
"updated": "0000-00-00 00:00:00",
"strain_name": "Janssen/gaston wowers ",
"usr_mobile": "+971/505040009",
"usr_image": "http://....19a.jpeg",
"usr_email": "...edo#gmail.com"
},
I am getting response in toast also, only json problem is thr ...
this is the php code:
public function searchPigeonList()
{
$data = (array)$this->request->input('json_decode');
$returnArr = $this->resp_arr;
$returnArr['pigeon_list'] = array();
$conn = ConnectionManager::get('default');
$query = "SELECT `pg`.*,`ps`.name as strain_name,`us`.mobile as usr_mobile,`us`.image as usr_image,`us`.email as usr_email FROM
`pigeons` as `pg` INNER JOIN `users` as `us` ON `pg`.`auth_token` = `us`.`uniq_id` INNER JOIN `pigeon_strain` as `ps` ON `ps`.`id` = `pg`.`strain_id` ";
// $query .= "WHERE `pg`.`country_code` = '".$data['country_code']."' ";
$cnt_cd = $data['country_code'];
$str_id = $data['strain_id'];
$dst = $data['distance'];
$conditions = array();
if($cnt_cd !="") {
$conditions[] = "`pg`.country_code='$cnt_cd'";
}
if($str_id !="") {
$conditions[] = "`pg`.strain_id='$str_id'";
}
if($dst !="") {
$conditions[] = "`pg`.distance='$dst'";
}
if (count($conditions) > 0) {
$query .= " WHERE " . implode(' AND ', $conditions);
$query .= " AND `pg`.status='approved'";
}
//echo $query;exit;
$stmt = $conn->execute($query);
$returnArr['status_code'] = 200;
$returnArr['status'] = "OK";
$returnArr['status_message'] = "Success";
$returnArr['pigeon_list'] = $stmt ->fetchAll('assoc');
if ($this->request->is('post')) {
echo json_encode($returnArr);
exit;
}
}
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("usr_image"));
names.add(obj.getString("pigeon_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
try replacing with
Try this.
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONObject responseObject=new JSONObject(response);
JSONArray json = responseObject.getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = json.getJSONObject(i);
//getting image url and title from json object
pid.add(obj.getInt(String.valueOf(TAG_PID)));
pname.add(obj.getString(TAG_PNAME));
pdetails.add(obj.getString(TAG_PDETAILS));
pmobile.add(obj.getString(TAG_MOBILE));
pemail.add(obj.getString(TAG_EMAIL));
images.add(obj.getString(TAG_IMAGE_URL));
names.add(obj.getString(TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
pmpigeonlistadapter.notifyDataSetChanged();
gridView.setAdapter(pmpigeonlistadapter);
}
I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})
I've this json:
{"data": [{"name" "category" "id" "picture":{"data":{"url":}}}]
My difficulty is how to parse the picture field. I tried with this code:
public class JSONParser {
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jGames = null;
try {
jGames = jObject.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
return getGames(jGames);
}
private List<HashMap<String, Object>> getGames(JSONArray jGames){
int gameCount = jGames.length();
List<HashMap<String, Object>> gameList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> game = null;
for(int i=0; i<gameCount;i++){
try {
game = getGame((JSONObject)jGames.get(i));
gameList.add(game);
} catch (JSONException e) {
e.printStackTrace();
}
}
return gameList;
}
private HashMap<String, Object> getGame(JSONObject jGame){
HashMap<String, Object> game = new HashMap<String, Object>();
String gameName = "";
String logo="";
String user = "";
try {
gameName = jGame.getString("name");
logo = jGame.getString("logo_url");
user = jGame.getString("daily_active_users");
String details ="Utenti attivi : " + user + "\n";
game.put("name", gameName);
game.put("logo_url", R.drawable.icon);
game.put("logo_path", logo);
game.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
return game;
}
}
this tutorial will help you Android JSON Parsing Tutorial