JsonArray, finding index? or multiple items in an array - android

in this example, i like to know which city is closer to Vancouver. Victoria , Washington or Texas? one I find shortest distance how can I see which destination_address this value belong to?
{
"destination_addresses" : [
"Victoria, BC, Canada",
"Texas, États-Unis",
"Washington, District de Columbia, États-Unis"
],
"origin_addresses" : [ "Vancouver, BC, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "135 km",
"value" : 134638
},
"duration" : {
"text" : "6 heures 37 minutes",
"value" : 23815
},
"status" : "OK"
},
{
"distance" : {
"text" : "3 457 km",
"value" : 3456694
},
"duration" : {
"text" : "7 jours 15 heures",
"value" : 658855
},
"status" : "OK"
},
{
"distance" : {
"text" : "5 000 km",
"value" : 4999636
},
"duration" : {
"text" : "11 jours 2 heures",
"value" : 956487
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I'm trying to find closest city to Vancouver by parsing the distance & find min distance. by finding that we see shortest distance belongs to Victoria. How canI say this min distance belongs to Victoria.
this is my code for finding closest city ( shortest distance)
public class MainActivity extends Activity {
HttpClient client;
double minDistance=0;
String destination_addresses;
JSONArray rows;
JSONArray elements;
final static String URL= "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&sensor=false";
protected void OnCreate (Bundle savedInstanceState ){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
client = new DefaultHttpClient();
}
public JSONObject ClosestObject (String Origin) throws ClientProtocolException, IOException , JSONException {
StringBuilder url= new StringBuilder (URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray locations = new JSONArray(data);
for (int i=0; i< locations.length(); i++){
rows= (JSONArray) locations.getJSONObject(2).get("rows");
elements= (JSONArray) locations.getJSONObject(0).get("elements");
String Value= elements.getJSONObject(i).toString();
double distanceValue = Double.parseDouble(Value);
if ( distanceValue< minDistance){
minDistance= distanceValue;
}
}
}

By the code you have given you are getting the JSON from Google url so you should read the documentation of the API, you will definitely get your answer there.
EDIT: and if you want to traverse the JSON array you can use yourjsonarray.getJSONObject(index).getString("Distance").

Try it :)
JSONObject bigData = new JSONObject(data);
rows = bigData.getJSONArray("rows");
elements = rows.getJSONObject(0).getJSONArray("elements");
JSONObject ob = elements.getJSONObject(0);
String value = ob.getJSONObject("duration").getString("value");//or "distance"
minDistance = Double.parseDouble(value);
int index = 0;
for (int i = 1; i < elements.length(); i++) {
ob = elements.getJSONObject(i);
value = ob.getJSONObject("duration").getString("value");//or "distance"
double distanceValue = Double.parseDouble(value);
if (distanceValue < minDistance) {
minDistance = distanceValue;
index = i;
}
}
JSONArray closers = bigData.getJSONArray("destination_addresses");
String closer = closers.getString(index);
Log.d("closer", closer);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Related

Android Studio - Parse from JSON ( Google Maps Api)

I need to extract the location type from where I am on the map for example from the following JSON :
(I deleted some of the irrelevant information in the fields)
{ "html_attributions" : [],
"results" : [
{ "business_status" : "OPERATIONAL", "geometry" :
{ "location" : { "lat" : 31.7895094,"lng" : 34.6444928},
"viewport" :
{"northeast" : {"lat" : 31.790,"lng" : 34.645}, "southwest" : {"lat" : 31.788,"lng" : 34.643} } },
"icon_mask_base_uri" : "",
"name" : "",
"opening_hours" : {"open_now" : true },
"photos" : [ { "height" : 709,
"html_attributions" : [],
"photo_reference" : "", "width" : 960 }],
"place_id" : "",
"plus_code" : {"compound_code" : "QJQV+RQ Ashdod, Israel",
"global_code" : "8G3PQJQV+RQ"},
"rating" : 3.9,
"reference" : "","scope" : "GOOGLE",
"types" : [ "electrician", "point_of_interest", "establishment" ],
"user_ratings_total" : 18,
"vicinity" : ""}],
"status" : "OK"}
I'm having trouble because the location type can be empty or can be a single location or can be several location types that come in an array.
The cases I need to handle:
If it's an array, I want only the first type (as in the attached example)
If it is a single location I want to extract it
If there is no location do not try to extract a location type at all
In the example above i need extract only "electrician" from types
This is how my code looks without extracting the types field:
public class FetchData extends AsyncTask<Object,String,String> {
String googleNearByPlacesData ;
GoogleMap googleMap;
String url;
String temp;
#Override
protected void onPostExecute(String s) {
//This is the exampale print
Log.d("json?" ,s);
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i= 0 ; i < jsonArray.length() ; i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject getLocation = jsonObject1.getJSONObject("geometry").
getJSONObject("location");
String lat = getLocation.getString("lat");
String lng = getLocation.getString("lng");
JSONObject getName = jsonArray.getJSONObject(i);
String name = getName.getString("name");
LatLng latLng = new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
MarkerOptions maekerOptions = new MarkerOptions();
maekerOptions.title(name);
maekerOptions.position(latLng);
googleMap.addMarker(maekerOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
} catch (JSONException e) {
e.printStackTrace();
}
}

How to read JSON array inside array inside an array

I am trying to read Values For Nearest Hospitals.
I am using google api and here is the return.
At first I was not reading latitude and longitude. Then the application would work fine. Now I read lat lang but i get data.size = 0;
{
"results" : [
{
"geometry" : {
"location" : {
"lat" : 33.7724766,
"lng" : 72.8127372
},
"viewport" : {
"northeast" : {
"lat" : 33.7739632802915,
"lng" : 72.8141296802915
},
"southwest" : {
"lat" : 33.7712653197085,
"lng" : 72.81143171970849
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/doctor-71.png",
"id" : "d05b6a41509c0b6dac573a6aa18453ab5ca6801e",
"name" : "HMC Female Dispensary",
"place_id" : "ChIJ_ddd9iyk3zgR32HNTt2Uhqw",
"plus_code" : {
"compound_code" : "QRC7+X3 Taxila, Pakistan",
"global_code" : "8J5JQRC7+X3"
},
"reference" : "ChIJ_ddd9iyk3zgR32HNTt2Uhqw",
"scope" : "GOOGLE",
"types" : [ "hospital", "health", "point_of_interest", "establishment" ],
"vicinity" : "Taxila"
}
Here is my code:
JSONObject obj = new JSONObject(new String(responseBody));
Log.e("Error", obj.toString());
JSONArray array = obj.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
JSONObject newobj = array.getJSONObject(i);
final Hospital hospital = new Hospital();
hospital.setId(newobj.getString("id"));
hospital.setName(newobj.getString("name"));
hospital.setPlace_id(newobj.getString("place_id"));
// hospital.setPhone_num();
if (newobj.has("rating"))
hospital.setRating(Double.parseDouble(newobj.getString("rating")));
hospital.setVicinity(newobj.getString("vicinity"));
JSONArray geometry = newobj.getJSONArray("geometry");
for (int j = 0; j < geometry.length(); j++) {
JSONObject jsonnewtwo = geometry.getJSONObject(j);
JSONArray location = jsonnewtwo.getJSONArray("location");
for (int k = 0; k < location.length(); k++) {
//get DATA here
JSONObject latlang = location.getJSONObject(k);
hospital.setLat(Double.parseDouble(latlang.getString("lat")));
hospital.setLng(Double.parseDouble(latlang.getString("lng")));
Log.e("hos", hospital.getLat() + "");
}
}
data.add(hospital);
Toast.makeText(MapsActivity.this , "Added" , Toast.LENGTH_LONG).show();
If i dont read lat and lang , then it works fine but if i read inner arrays using above method , the size of Arraylist data is 0.
What is issue?
geometry is a Json Object and you are trying to convert it to JSONArray. Check this line. JSONArray geometry = newobj.getJSONArray("geometry");
JSONObject geometry = newobj.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
Log.w("Latitude", location.getString("lat"))
Log.w("Longitude", location.getString("lng"))

getting a string from JSONobject under another JSONobject

My json link to json
This is the code to fetch the items. I am getting the error while fetching the photo_reference. I know that photos is a JSONarray and inside that a JSONobject is there. The error is that it shows as no value for photos. how to get the array and how to fetch the photo_reference string? I'm new to JSON and this is quite difficult for me. Log cat is also shared. Thank you in advance.
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("results");
for (int i = 0; i<array.length();i++)
{
//get the photo reference from json of google place web api
JSONObject o = array.getJSONObject(i);
Places item = new Places();
JSONArray photo = o.getJSONArray("photos");
JSONObject photos = photo.getJSONObject(0);
String ph_ref = photos.getString("photo_reference");
String id = o.getString("id");
String name = o.getString("name");
if (o.has("rating")) {
String rat = o.getString("rating");
item.setRating(rat);
}else{
item.setRating("0");
}
org.json.JSONException: No value for photos
Logcat
org.json.JSONException: No value for photos
at org.json.JSONObject.get(JSONObject.java:389)
at org.json.JSONObject.getJSONArray(JSONObject.java:584)
UPDATE
MY SOLUTION
if (o.has("photos")){
JSONArray photo = o.getJSONArray("photos");
JSONObject photos = photo.getJSONObject(0);
String ph_ref = photos.getString("photo_reference");
item.setPh_ref(ph_ref);
}
else
item.setPh_ref("no photos available");
Some items doesn't have the photos object in the json.
So you need to check the photo object,
JSONArray photo = o.getJSONArray("photos");
if(photo != null) {
JSONObject photos = photo.getJSONObject(0);
}
Some of the items just don't have "photos" inside. One of them is:
{
"geometry" : {
"location" : {
"lat" : 26.1744046,
"lng" : 91.7769246
},
"viewport" : {
"northeast" : {
"lat" : 26.1757411802915,
"lng" : 91.7782234802915
},
"southwest" : {
"lat" : 26.1730432197085,
"lng" : 91.77552551970849
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/lodging-71.png",
"id" : "f66820fca7c21cb6783fe27a996af3379ed7140e",
"name" : "OYO 5332 Parnil Palace",
"place_id" : "ChIJ0S48-Z5ZWjcRBXSBd8gS9q4",
"rating" : 4.5,
"reference" : "CmRSAAAAlzfMwWtNWJb8fFFyzsqNBxyZgbfbR4IPZLP2qQVph1NBgZqEwolpKNc7rRXBAQVFX4ph31iYvCrFM77v5QqDY8gEIWHBJMdW9vqWSiMlDCDF-_r6N4AUviMXwH6xTq64EhAFOGo0wihXKEy8GPtQayxiGhS6SNxnJ6DI58p9uwhSek-ov2pLJA",
"scope" : "GOOGLE",
"types" : [ "lodging", "point_of_interest", "establishment" ],
"vicinity" : "Zoo Road, Zoo Tiniali, Guwahati"
},

URL class rendering - Invalid_Request with next_page_token

In my Android application the user can select categories (cafe, restaurant, ...) of which places he wants to see.
I get result from the google-places-api with a next_page_token, when I use the following url:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=cafe+in+Elfde-Liniestraat%2C+Hasselt%2C+Belgium&pagetoken=ClRHAAAAqYa7IpwMQH3q1DyinfsMnkuOaZg8wQrp0pvzarv13pwqruqT2YfaEry6v_d-L4d_TC13G6iHuPz-rc1KbI6XRE01rB5CuXcHISu-CI_CaKESEMUxSjHhHDNee4xbr2tPEZcaFPvO6xlRDjs-5AixyD9vamWwTGlU&sensor=true&key=<mykey>
or this url:
https://maps.googleapis.com/maps/api/place/textsearch/json?pagetoken=ClRHAAAAqYa7IpwMQH3q1DyinfsMnkuOaZg8wQrp0pvzarv13pwqruqT2YfaEry6v_d-L4d_TC13G6iHuPz-rc1KbI6XRE01rB5CuXcHISu-CI_CaKESEMUxSjHhHDNee4xbr2tPEZcaFPvO6xlRDjs-5AixyD9vamWwTGlU&sensor=true&key=<mykey>
I get a INVALID_REQUEST.
This is the code I use to run and fetch the results:
#Override
protected ArrayList<String> doInBackground(String... params) {
// When more then one category is selected, this character needs to be after it.
final String DELIMITINGCHARACTER = "|";
// Add all the categories to a variable to put later on in the URL.
String myTypes = "";
for (String category : params){
// A category must be lowercase letters only.
category = category.toLowerCase();
// A category may not display a whitespace.
// The whitespace(s) must be replaced with a '_'.
category = category.replaceAll(" ", "_");
myTypes += category + DELIMITINGCHARACTER;
}
// Delete if the string ends with the delimitingcharachter the delimitingcharacter!
if (myTypes.endsWith("|")){
myTypes = myTypes.substring(0, myTypes.length() - 1);
}
ArrayList<String> myPointsOfInterest = new ArrayList<String>();
try{
String urlString;
String urlData;
//String urlApi = "&sensor=true&key=<myKey>"; // Key 1
String urlApi = "&sensor=true&key=<myKey>"; // Key 2
if (_txtFindLocation.getText().length() > 0){
urlString = "maps.googleapis.com/maps/api/place/textsearch/json?";
urlData = "query=" + URLEncoder.encode(myTypes, "UTF-8") + "+in+"
+ URLEncoder.encode(_txtFindLocation.getText().toString(), "UTF-8");
}
else{
urlString = "maps.googleapis.com/maps/api/place/search/json?";
urlData = "location=" + _myCurrentPosition.getLatitudeE6() / 1e6 + "," + _myCurrentPosition.getLongitudeE6() / 1e6
+ "&radius=5000&types=" + URLEncoder.encode(myTypes, "UTF-8");
}
ArrayList<String> myJsonString = new ArrayList<String>();
myJsonString.add(getDataOfUrl(urlString, urlData, urlApi, null));
for (String jsonString : myJsonString){
// Turn String into a JSON Object.
JSONObject jsonPredictionsObject = new JSONObject(jsonString);
String urlToken = jsonPredictionsObject.optString("next_page_token");
if (urlToken != ""){
myJsonString.add(getDataOfUrl(urlString, urlData, urlApi, "&pagetoken=" + urlToken));
}
}
Log.d("MainActivity", "size of myJsonString " + String.valueOf(myJsonString.size()));
for (String jsonString : myJsonString){
Log.d("MainActivity", jsonString);
// Turn String into a JSON Object.
JSONObject jsonPredictionsObject = new JSONObject(jsonString);
// Get a JSON Array that is inside the JSON Object.
JSONArray jsonPredictionsArray = jsonPredictionsObject.getJSONArray("results");
for (int i = 0; i < jsonPredictionsArray.length(); i++){
jsonPredictionsObject = (JSONObject) jsonPredictionsArray.get(i);
final String name = jsonPredictionsObject.getString("name");
final String vicinity = jsonPredictionsObject.optString("vicinity").compareTo("") != 0 ? jsonPredictionsObject.optString("vicinity") : jsonPredictionsObject.optString("formatted_address");
final JSONObject geometryObject = jsonPredictionsObject.getJSONObject("geometry");
final JSONObject locationObject = geometryObject.getJSONObject("location");
final JSONArray typesArray = jsonPredictionsObject.getJSONArray("types");
final double latitude = locationObject.getDouble("lat");
final double longitude = locationObject.getDouble("lng");
String types = "";
for (int t = 0; t < typesArray.length(); t++){
String type = typesArray.getString(t);
type = type.toLowerCase();
type = type.replaceAll("_", " ");
types += type + " - ";
}
types = types.substring(0, types.length() - 2);
myPointsOfInterest.add(String.valueOf(latitude) + DELIMITINGCHARACTER +
String.valueOf(longitude) + DELIMITINGCHARACTER + types +
DELIMITINGCHARACTER + name + DELIMITINGCHARACTER + vicinity);
}
}
}
catch (IOException e){
Log.e("Search points of interest", "GetPointsOfinterest: doInBackGround", e);
}
catch (JSONException e){
Log.e("Search points of interest", "GetPointsOfinterest: doInBackGround", e);
}
return myPointsOfInterest;
}
public String getDataOfUrl(String urlString, String urlData, String urlApi, String urlToken){
try{
URL myURL;
if (urlToken == null) {
myURL = new URL("https://" + urlString + urlData + urlApi);
}
else {
Log.d("URL INPUT", "https://" + urlString + urlData + urlToken + urlApi);
myURL = new URL("https://" + urlString + urlData + urlToken + urlApi);
}
URLConnection myURLConnection = myURL.openConnection();
BufferedReader myBufferReader = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
String strLine;
StringBuffer strBuffer = new StringBuffer();
// Take Google's legible JSON and turn it into on big String.
while((strLine = myBufferReader.readLine()) != null){
strBuffer.append(strLine);
}
Log.d("URL OUTPUT", strBuffer.toString());
return strBuffer.toString();
}
catch (IOException e){
Log.e("getDataOfUrl", "Error: ", e);
}
return null;
}
This is the output of logcat:
11-03 14:47:13.832: D/URL OUTPUT(19532): { "html_attributions" : [], "next_page_token" : "ClRHAAAAqYa7IpwMQH3q1DyinfsMnkuOaZg8wQrp0pvzarv13pwqruqT2YfaEry6v_d-L4d_TC13G6iHuPz-rc1KbI6XRE01rB5CuXcHISu-CI_CaKESEMUxSjHhHDNee4xbr2tPEZcaFPvO6xlRDjs-5AixyD9vamWwTGlU", "results" : [ { "formatted_address" : "Meldertstraat 42, Hasselt, België", "geometry" : { "location" : { "lat" : 50.9311660, "lng" : 5.3423240 } }, "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png", "id" : "e6ba73e5b439dddb83aaefc94c71954da0cb0268", "name" : "Café Café", "rating" : 4.40, "reference" : "CnRpAAAAdVZpUI4NKwsAiQTOjbYG9psNbU7awZkS6_8Ee4r3AvCKhpqWeiDqdof7zYmoUZWKj0A8rOwtncSa1YFVNNo6RxFmmHvuNdWCaucTqkuSSDw8E2o0pf5E6EiMj-7-Hd5xBzDtC0j9d5lLcVWW3AQy1xIQRwgfWwrZkyK65blCeGqhFhoUB9kTW5QVD9sNNuF75MvVewYTcxA", "types" : [ "cafe", "food", "establishment" ] }, { "formatted_address" : "Kempischesteenweg 27, Hasselt, België", "geometry" : { "location" : { "lat" : 50.9350770, "lng" : 5.3397760 } }, "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png", "id" : "dc66d311b3c4f5d1a87d5959dfdbc7616ad10b24", "name" : "Oberonn", "opening_hours" : { "open_now" : true }, "reference" : "CnRlAAAA5q-rz_aOTWsFGQIJz_6zyLbXIczXOTq4PVFxniOjxsCwnw7uIfY8tu7Jk-QbJ-arMWgdClnSpX28q2SqxD8021LGWcaf4Sgo9MaXWpoD6c4TSagyVO9_l_HUXgMoOFJzhHG_NH6z-t1DPxT1zD19PhIQ2gBP9cLazKeB96ZDTpFdsxoUVGB2Ddhrq6JUoTJgrHGL-SINOWk", "types" : [ "cafe", "food", "establishment" ] }, { "formatted_address" : "Willekensmolenstraat 41, Hasselt, België", "geometry" : { "location" : { "lat" : 50.9316830, "lng" : 5.3470750 } }, "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png", "id" : "04937541c2bf71ebec7ac13d506dbbd2727e1ce3", "name" : "Den Drossaerd", "reference" : "CnRqAAAA0cPmuMx0_J4x-o-yn0oT1D3kD-IHYAQPotAPPeDD3DWh2FXkD89kCsYoUGDLBlH2mKY6ju18JyCHvc4W_izLcd6TUOIoXrbUCyrtxOL4sTAFb41kH1aFT4dOBgvigYrGIcV8Qbzq-K4YGL3t7pnf1hIQKmUp-LLqtGHb4waYi2nq8hoU3VgwykpytoSUUPe2Ue1HmPrMRtE", "types" : [ "cafe", "food", "establishment" ] }, { "formatted_address" : "Leopoldplein 1, Hasselt, België", "geometry" : { "location" : { "lat" : 50.9275810, "lng" : 5.3363830 } }, "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/lodging-71.png", "id" : "cc30d6f4e6b0db1ed6dfd17bac118bbf78f194ae", "name" : "Century (Hotel)", "rating" : 3.80, "reference" : "CnRsAAAAfw4ucOBllDjMCtRU9epYQelpKHRx3u8JR8jr4I5jFzJsktNn3Un-3LjKKWtXCk3Unofi_6RhPFw9Tp8VU_Z7i-WOa00P-pirtCDjQPxg7sp470Mgh6_6PQspGG39H3k-VIMuUz9HWmoP3sPjump6SRIQTp1LZghfi-_HVaMfQArGPxoU-6ogK2IGMiueMEXP9mFiHlGJmo8", "types" : [ "lodging", "establishment" ] }, { "formatted_address" : "Maastrichterstraat 30, Hasselt, België", "geometry" : { "location" : { "lat" : 50.9295410, "lng" : 5.3391230 } }, "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png", "id" : "352f9da4642588aba419353487b210baeb30ddd3", "name" : "In De Kleine Hal", "reference" : "CnRuAAAAAlnMpdiL4Kluiw1T0-QgKWFv9wwWvrSY4w-B7SLI7gvpqT0FYaMTl6DhxncPLqRyxOTWxw3DP3r1XvNHDKXnAb3eRM-gZYwIqbvzVq62zEZgGw0usQgf48mAWOrDpegdNLnEFRYkIduRwlDMDyIOyBIQlDs9BozH4m_gE-dZKZf7yxoUqw0H_HT_IQnLaVm0YwG1QV7o3kg", "types" : [ "cafe", "food", "establishment" ] }, { "formatted_address" : "Fruitmarkt 32, Hasselt, België", "geometry" : { "location" : { "lat" : 50.9299760, "lng" : 5.3393550 } }, "icon" : "http://maps.gstatic.com/mapfiles
11-03 14:47:13.864: D/URL INPUT(19532): https://maps.googleapis.com/maps/api/place/textsearch/json?query=cafe+in+Elfde-Liniestraat%2C+Hasselt%2C+Belgium&pagetoken=ClRHAAAAqYa7IpwMQH3q1DyinfsMnkuOaZg8wQrp0pvzarv13pwqruqT2YfaEry6v_d-L4d_TC13G6iHuPz-rc1KbI6XRE01rB5CuXcHISu-CI_CaKESEMUxSjHhHDNee4xbr2tPEZcaFPvO6xlRDjs-5AixyD9vamWwTGlU&sensor=true&key=<myKey>
11-03 14:47:13.989: D/URL OUTPUT(19532): { "html_attributions" : [], "results" : [], "status" : "INVALID_REQUEST"}
PS: When I past the code in my browser (with next_page_token) both ways are correct, only I my Android app I get no valid data. AND yes I have a API Key, but I removed it here from both the code and my logcat output.
Anyone a idea what I'm doing wrong here?
EDIT
When I hardcode my url (with next-page-token) in Android, and afterwords let it run. I get the data that I expected, so no Invalid_Request is returned. The problems lays somewhere in building the url in Android, or the usage of the URL-class.
Found the answer on my own question: after a while, I just needed to check my output of logcat better.
The times of the request en times when the data was sent back from google.
output time of request 1: 14:47:13:832
input time of request 2: 14:47:13:864
output time of request 2: 14:47:13:989
These times are to close to each other, in my opinion Google thought I was a spammer/hacker or something and denied me access to the server on the second request.
The solution for me is wait 1 second if there is a next_page_token and then send the followup request.

how can i put req and response from android using json?

I am new to android json i want put the req and get the response from the google matrix api server in android i want send the req :
http://maps.googleapis.com/maps/api/distancematrix/json?origins=Hyderabad,Andhra%20Pradesh,India&destinations=Eluru,Andhra%20pradesh,India&mode=driving&language=fr-FR&sensor=false
and that url returs the output is as fallows i want extract the km value from that result. :
{
"destination_addresses" : [ "Eluru, Andhra Pradesh, Inde" ],
"origin_addresses" : [ "Hyderabad, Andhra Pradesh, Inde" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "330 km",
"value" : 330316
},
"duration" : {
"text" : "5 heures 1 minute",
"value" : 18052
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
How to get the distance value and print in the app console?
In the Following shown way you can retrieve the km from your JSON Output.
JSONObject jobj = new JSONObject(your result);
JSONObject json;
json = jobject;
JSONArray jrowsArray = json.getJSONArray("rows");
for(int i=0;i<jrowsArray.length;i++){
JSONArray jElementsArray = jrowsArray.getJSONArray("elements");
for(int j=0;j<jElementsArray.length;j++){
JSONObject jDistance = jElementsArray.getJSONObject("distance");
String distancekm = jDistance.getString("text");
}
}

Categories

Resources