Exception in finding driving distance between two geopiont - android
I want to find out driving distance between two latitude and longitude.
this is my code
private String GetDistance(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + ","
+ origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String urlString = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
// get the JSON And parse it to get the directions data.
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(
inStream));
String temp,response = "";
while ((temp = bReader.readLine()) != null) {
// Parse data
response += temp;
}
// Close the reader, stream & connection
bReader.close();
inStream.close();
urlConnection.disconnect();
// Sort out JSONresponse
// JSONObject object = (JSONObject) new JSONTokener(response)
// .nextValue();
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("routes");
// Log.d("JSON","array: "+array.toString());
// Routes is a combination of objects and arrays
JSONObject routes = array.getJSONObject(0);
// Log.d("JSON","routes: "+routes.toString());
String summary = routes.getString("summary");
Log.d("JSON","summary: "+summary);
JSONArray legs = routes.getJSONArray("legs");
// Log.d("JSON","legs: "+legs.toString());
JSONObject steps = legs.getJSONObject(0);
// Log.d("JSON","steps: "+steps.toString());
JSONObject distance = steps.getJSONObject("distance");
// Log.d("JSON","distance: "+distance.toString());
sDistance = distance.getString("text");
iDistance = distance.getInt("value");
} catch (Exception e) {
// TODO: handle exception
return e.toString();
}
return sDistance;
}
and i am getting a exception
org.json.JSONException:Index 0 out of range [0..0)
this is my stacktrace
Ljava.lang.StackTraceElement;#41019be8
please help me out what is the problem.
First of all, don't hardcode any position(like 0) to get from array. Bcs, the array may be empty.
That's what happened in your case. One of your array or legs JSONArray is empty but you are trying to get the 0th position of them. So,it is throwing index out of range exception.
To get the values from an array better use for loop. An example code snippet is:
Log.v("array-length--", ""+array.length());
for(int i=0; i < array.length();i++)
{
// Routes is a combination of objects and arrays
JSONObject routes = array.getJSONObject(i);
// Log.d("JSON","routes: "+routes.toString());
String summary = routes.getString("summary");
Log.d("JSON","summary: "+summary);
JSONArray legs = routes.getJSONArray("legs");
// Log.d("JSON","legs: "+legs.toString());
Log.v("legs-length--", ""+legs.length());
for(int j=0; j < legs.length(); j++)
{
JSONObject steps = legs.getJSONObject(j);
// Log.d("JSON","steps: "+steps.toString());
JSONObject distance = steps.getJSONObject("distance");
// Log.d("JSON","distance: "+distance.toString());
sDistance = distance.getString("text");
iDistance = distance.getInt("value");
}
}
Related
How to get latitude and longitude bounds by city/country name android
I am searching Latitude and longitude bounds in google map for a specific city. I got the example to implement for country name India. private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(new LatLng(23.63936, 68.14712), new LatLng(28.20453, 97.34466)); Now, I want to set it for my chosen country. Where to find those two point Latitude and Longitude for specific area.
Check the below code String location=cityName; String inputLine = ""; String result = "" location=location.replaceAll(" ", "%20"); String myUrl="http://maps.google.com/maps/geo?q="+location+"&output=csv"; try{ URL url=new URL(myUrl); URLConnection urlConnection=url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((inputLine = in.readLine()) != null) { result=inputLine; } String lat = result.substring(6, result.lastIndexOf(",")); String longi = result.substring(result.lastIndexOf(",") + 1); } catch(Exception e){ e.printStackTrace(); }
google direction gives 0 values
hey I have used google direction to get duration it's working but sometime it return 0 value to json array routs. when I tested a day after return a value. is there any limitation for google direction request per day ? and here is my function to get duration public String getDistanceInfo(LatLng origin, LatLng dest) { StringBuilder stringBuilder = new StringBuilder(); String str_origin = "origin=" + origin.latitude + "," + origin.longitude; // Destination of route String str_dest = "destination=" + dest.latitude + "," + dest.longitude; String dura = ""; try { String sensor = "sensor=false"; String output = "json"; String mode = "mode=walking"; String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode; // Output format // Building the url to the web service String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters; //String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + str_origin + "," + str_dest + "&destination=" + destinationAddress + "&mode=driving&sensor=false"; HttpPost httppost = new HttpPost(url); HttpClient client = new DefaultHttpClient(); HttpResponse response; stringBuilder = new StringBuilder(); response = client.execute(httppost); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); JSONArray array = jsonObject.getJSONArray("routes"); JSONObject routes = array.getJSONObject(0); JSONArray legs = routes.getJSONArray("legs"); JSONObject steps = legs.getJSONObject(0); JSONObject duration = steps.getJSONObject("duration"); dura = duration.getString("text"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return dura; } org.json.JSONException: Index 0 out of range [0..0) org.json.JSONArray.get(JSONArray.java:282) org.json.JSONArray.getJSONObject(JSONArray.java:510)
Check to see if you are also getting something like this too in your JSON response apart from 0 for the duration. {"status":"OVER_QUERY_LIMIT","routes":[]}. This means that you are exceeding the limits of the Direction API usage. Please note that for standard version there are only 2,500 free directions requests per day available. If you need to request more, their are additional charges associated. Check the official documentation on Google Maps Directions API Usage Limits more details.
Fetching Location Distance issue sending 0.0
I am using the following code the fetching the distance between difference latitude and longitude.Some time it works fine but some time it return the 0.0. I can't understand the reason why it happen. I have enable both GPS and Network My code is.. public static String getDistanceOnRoad(String latitude, String longitude, String prelatitute, String prelongitude) { String result_in_kms = ""; float num_in_Km=0; String url = "http://maps.google.com/maps/api/directions/xml?origin=" + latitude + "," + longitude + "&destination=" + prelatitute + "," + prelongitude + "&sensor=false&units=metric"; String tag[] = { "text" }; HttpResponse response = null; try { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); response = httpClient.execute(httpPost, localContext); InputStream is = response.getEntity().getContent(); DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document doc = builder.parse(is); if (doc != null) { NodeList nl; ArrayList args = new ArrayList(); for (String s : tag) { nl = doc.getElementsByTagName(s); if (nl.getLength() > 0) { Node node = nl.item(nl.getLength() - 1); args.add(node.getTextContent()); } else { args.add(" - "); } } result_in_kms = String.format("%s", args.get(0)); //result come with 'm' and 'km' tag so remove this tag String num=stripNonDigits(result_in_kms); //if result in KM then does not devide by 1000 if(!isdisIn_M_or_KM(result_in_kms)){ num_in_Km=Float.valueOf(num)/1000; } else num_in_Km=Float.valueOf(num); Log.i("", ""); } } catch (Exception e) { e.printStackTrace(); } return String.valueOf(num_in_Km); }
For Finding the distance using GPS, There is no Need of Network Connection. GPS will provide the Latitude and Longitude based on the the time interval you apply. kindly refer the below link Calculate distance between two latitude-longitude points? (Haversine formula)
Problema with JSONObject and JSONArray
JSONObject result = new JSONObject("{\"result\":{\"players\":[{\"account_id\":4294967295,\"player_slot\":0,\"hero_id\":66,\"item_0\":180,\"item_1\":92,\"item_2\":42,\"item_3\":0,\"item_4\":0,\"item_5\":46,\"kills\":0,\"deaths\":10,\"assists\":8,\"leaver_status\":0,\"gold\":311,\"last_hits\":28,\"denies\":0,\"gold_per_min\":200,\"xp_per_min\":316,\"gold_spent\":5743,\"hero_damage\":3441,\"tower_damage\":188,\"hero_healing\":3515,\"level\":15,\"ability_upgrades\":[{\"ability\":5330,\"time\":189,\"level\":1},{\"ability\":5328,\"time\":385,\"level\":2},{\"ability\":5330,\"time\":479,\"level\":3},{\"ability\":5328,\"time\":539,\"level\":4},{\"ability\":5330,\"time\":791,\"level\":5},{\"ability\":5331,\"time\":857,\"level\":6},{\"ability\":5330,\"time\":985,\"level\":7},{\"ability\":5329,\"time\":1068,\"level\":8},{\"ability\":5328,\"time\":1194,\"level\":9},{\"ability\":5328,\"time\":1251,\"level\":10},{\"ability\":5331,\"time\":1415,\"level\":11},{\"ability\":5329,\"time\":1933,\"level\":12},{\"ability\":5329,\"time\":1970,\"level\":13},{\"ability\":5329,\"time\":2109,\"level\":14},{\"ability\":5002,\"time\":2342,\"level\":15}]},{\"account_id\":4294967295,\"player_slot\":1,\"hero_id\":88,\"item_0\":202,\"item_1\":29,\"item_2\":44,\"item_3\":0,\"item_4\":0,\"item_5\":0,\"kills\":7,\"deaths\":8,\"assists\":7,\"leaver_status\":0,\"gold\":138,\"last_hits\":31,\"denies\":2,\"gold_per_min\":234,\"xp_per_min\":344,\"gold_spent\":6435,\"hero_damage\":9492,\"tower_damage\":74,\"hero_healing\":0,\"level\":15,\"ability_upgrades\":[{\"ability\":5462,\"time\":298,\"level\":1},{\"ability\":5464,\"time\":371,\"level\":2},{\"ability\":5462,\"time\":445,\"level\":3},{\"ability\":5463,\"time\":555,\"level\":4},{\"ability\":5462,\"time\":746,\"level\":5},{\"ability\":5465,\"time\":881,\"level\":6},{\"ability\":5462,\"time\":942,\"level\":7},{\"ability\":5463,\"time\":979,\"level\":8},{\"ability\":5464,\"time\":1225,\"level\":9},{\"ability\":5465,\"time\":1365,\"level\":10},{\"ability\":5464,\"time\":1367,\"level\":11},{\"ability\":5463,\"time\":1966,\"level\":12},{\"ability\":5464,\"time\":1967,\"level\":13},{\"ability\":5463,\"time\":2361,\"level\":14},{\"ability\":5002,\"time\":2482,\"level\":15}]},{\"account_id\":4294967295,\"player_slot\":2,\"hero_id\":13,\"item_0\":36,\"item_1\":41,\"item_2\":40,\"item_3\":104,\"item_4\":46,\"item_5\":63,\"kills\":3,\"deaths\":13,\"assists\":5,\"leaver_status\":0,\"gold\":1738,\"last_hits\":97,\"denies\":4,\"gold_per_min\":284,\"xp_per_min\":357,\"gold_spent\":6694,\"hero_damage\":6801,\"tower_damage\":26,\"hero_healing\":0,\"level\":16,\"ability_upgrades\":[{\"ability\":5069,\"time\":130,\"level\":1},{\"ability\":5071,\"time\":280,\"level\":2},{\"ability\":5072,\"time\":349,\"level\":3},{\"ability\":5069,\"time\":380,\"level\":4},{\"ability\":5071,\"time\":531,\"level\":5},{\"ability\":5073,\"time\":639,\"level\":6},{\"ability\":5069,\"time\":759,\"level\":7},{\"ability\":5069,\"time\":824,\"level\":8},{\"ability\":5071,\"time\":1119,\"level\":9},{\"ability\":5071,\"time\":1201,\"level\":10},{\"ability\":5073,\"time\":1319,\"level\":11},{\"ability\":5072,\"time\":1380,\"level\":12},{\"ability\":5072,\"time\":1429,\"level\":13},{\"ability\":5072,\"time\":1691,\"level\":14},{\"ability\":5002,\"time\":2168,\"level\":15},{\"ability\":5073,\"time\":2399,\"level\":16}]},{\"account_id\":4294967295,\"player_slot\":3,\"hero_id\":59,\"item_0\":79,\"item_1\":63,\"item_2\":43,\"item_3\":37,\"item_4\":32,\"item_5\":17,\"kills\":11,\"deaths\":9,\"assists\":4,\"leaver_status\":0,\"gold\":100,\"last_hits\":90,\"denies\":16,\"gold_per_min\":319,\"xp_per_min\":397,\"gold_spent\":11024,\"hero_damage\":18103,\"tower_damage\":913,\"hero_healing\":723,\"level\":17,\"ability_upgrades\":[{\"ability\":5272,\"time\":236,\"level\":1},{\"ability\":5273,\"time\":298,\"level\":2},{\"ability\":5272,\"time\":366,\"level\":3},{\"ability\":5273,\"time\":476,\"level\":4},{\"ability\":5272,\"time\":549,\"level\":5},{\"ability\":5274,\"time\":650,\"level\":6},{\"ability\":5272,\"time\":827,\"level\":7},{\"ability\":5273,\"time\":893,\"level\":8},{\"ability\":5273,\"time\":958,\"level\":9},{\"ability\":5271,\"time\":1058,\"level\":10},{\"ability\":5274,\"time\":1131,\"level\":11},{\"ability\":5271,\"time\":1262,\"level\":12},{\"ability\":5271,\"time\":1356,\"level\":13},{\"ability\":5271,\"time\":1574,\"level\":14},{\"ability\":5002,\"time\":1715,\"level\":15},{\"ability\":5274,\"time\":2099,\"level\":16},{\"ability\":5002,\"time\":2449,\"level\":17}]},{\"account_id\":4294967295,\"player_slot\":4,\"hero_id\":1,\"item_0\":11,\"item_1\":145,\"item_2\":63,\"item_3\":46,\"item_4\":147,\"item_5\":0,\"kills\":2,\"deaths\":6,\"assists\":3,\"leaver_status\":0,\"gold\":2658,\"last_hits\":258,\"denies\":15,\"gold_per_min\":442,\"xp_per_min\":535,\"gold_spent\":12454,\"hero_damage\":2703,\"tower_damage\":689,\"hero_healing\":0,\"level\":19,\"ability_upgrades\":[{\"ability\":5004,\"time\":141,\"level\":1},{\"ability\":5003,\"time\":258,\"level\":2},{\"ability\":5003,\"time\":345,\"level\":3},{\"ability\":5005,\"time\":444,\"level\":4},{\"ability\":5003,\"time\":551,\"level\":5},{\"ability\":5006,\"time\":693,\"level\":6},{\"ability\":5003,\"time\":785,\"level\":7},{\"ability\":5005,\"time\":935,\"level\":8},{\"ability\":5005,\"time\":1063,\"level\":9},{\"ability\":5005,\"time\":1070,\"level\":10},{\"ability\":5006,\"time\":1096,\"level\":11},{\"ability\":5004,\"time\":1436,\"level\":12},{\"ability\":5004,\"time\":1483,\"level\":13},{\"ability\":5004,\"time\":1565,\"level\":14},{\"ability\":5002,\"time\":1647,\"level\":15},{\"ability\":5006,\"time\":1728,\"level\":16},{\"ability\":5002,\"time\":1867,\"level\":17},{\"ability\":5002,\"time\":2023,\"level\":18},{\"ability\":5002,\"time\":2211,\"level\":19}]},{\"account_id\":4294967295,\"player_slot\":128,\"hero_id\":32,\"item_0\":208,\"item_1\":71,\"item_2\":170,\"item_3\":63,\"item_4\":22,\"item_5\":0,\"kills\":9,\"deaths\":4,\"assists\":10,\"leaver_status\":0,\"gold\":2738,\"last_hits\":93,\"denies\":3,\"gold_per_min\":399,\"xp_per_min\":441,\"gold_spent\":12586,\"hero_damage\":11004,\"tower_damage\":2995,\"hero_healing\":0,\"level\":17,\"ability_upgrades\":[{\"ability\":5143,\"time\":122,\"level\":1},{\"ability\":5144,\"time\":268,\"level\":2},{\"ability\":5144,\"time\":329,\"level\":3},{\"ability\":5143,\"time\":452,\"level\":4},{\"ability\":5142,\"time\":637,\"level\":5},{\"ability\":5145,\"time\":720,\"level\":6},{\"ability\":5143,\"time\":853,\"level\":7},{\"ability\":5144,\"time\":923,\"level\":8},{\"ability\":5144,\"time\":1108,\"level\":9},{\"ability\":5145,\"time\":1370,\"level\":10},{\"ability\":5142,\"time\":1371,\"level\":11},{\"ability\":5143,\"time\":1513,\"level\":12},{\"ability\":5142,\"time\":1632,\"level\":13},{\"ability\":5142,\"time\":1855,\"level\":14},{\"ability\":5002,\"time\":1928,\"level\":15},{\"ability\":5145,\"time\":2104,\"level\":16},{\"ability\":5002,\"time\":2139,\"level\":17}]},{\"account_id\":89395208,\"player_slot\":129,\"hero_id\":92,\"item_0\":79,\"item_1\":180,\"item_2\":36,\"item_3\":90,\"item_4\":0,\"item_5\":0,\"kills\":3,\"deaths\":3,\"assists\":17,\"leaver_status\":0,\"gold\":2200,\"last_hits\":31,\"denies\":1,\"gold_per_min\":298,\"xp_per_min\":336,\"gold_spent\":9388,\"hero_damage\":8401,\"tower_damage\":1073,\"hero_healing\":867,\"level\":15,\"ability_upgrades\":[{\"ability\":5482,\"time\":213,\"level\":1},{\"ability\":5481,\"time\":310,\"level\":2},{\"ability\":5481,\"time\":352,\"level\":3},{\"ability\":5480,\"time\":440,\"level\":4},{\"ability\":5481,\"time\":611,\"level\":5},{\"ability\":5480,\"time\":693,\"level\":6},{\"ability\":5481,\"time\":881,\"level\":7},{\"ability\":5483,\"time\":1098,\"level\":8},{\"ability\":5480,\"time\":1266,\"level\":9},{\"ability\":5480,\"time\":1489,\"level\":10},{\"ability\":5483,\"time\":1553,\"level\":11},{\"ability\":5482,\"time\":1919,\"level\":12},{\"ability\":5482,\"time\":1990,\"level\":13},{\"ability\":5482,\"time\":2146,\"level\":14},{\"ability\":5002,\"time\":2476,\"level\":15}]},{\"account_id\":4294967295,\"player_slot\":130,\"hero_id\":53,\"item_0\":152,\"item_1\":98,\"item_2\":96,\"item_3\":63,\"item_4\":65,\"item_5\":88,\"kills\":7,\"deaths\":6,\"assists\":17,\"leaver_status\":0,\"gold\":3534,\"last_hits\":277,\"denies\":5,\"gold_per_min\":642,\"xp_per_min\":751,\"gold_spent\":16900,\"hero_damage\":12718,\"tower_damage\":1597,\"hero_healing\":0,\"level\":23,\"ability_upgrades\":[{\"ability\":5247,\"time\":169,\"level\":1},{\"ability\":5246,\"time\":285,\"level\":2},{\"ability\":5247,\"time\":336,\"level\":3},{\"ability\":5245,\"time\":479,\"level\":4},{\"ability\":5247,\"time\":531,\"level\":5},{\"ability\":5248,\"time\":641,\"level\":6},{\"ability\":5247,\"time\":685,\"level\":7},{\"ability\":5246,\"time\":746,\"level\":8},{\"ability\":5246,\"time\":870,\"level\":9},{\"ability\":5246,\"time\":1080,\"level\":10},{\"ability\":5248,\"time\":1103,\"level\":11},{\"ability\":5245,\"time\":1328,\"level\":12},{\"ability\":5245,\"time\":1370,\"level\":13},{\"ability\":5245,\"time\":1502,\"level\":14},{\"ability\":5002,\"time\":1614,\"level\":15},{\"ability\":5248,\"time\":1890,\"level\":16},{\"ability\":5002,\"time\":1943,\"level\":17},{\"ability\":5002,\"time\":2180,\"level\":18},{\"ability\":5002,\"time\":2299,\"level\":19},{\"ability\":5002,\"time\":2386,\"level\":20},{\"ability\":5002,\"time\":2396,\"level\":21},{\"ability\":5002,\"time\":2458,\"level\":22},{\"ability\":5002,\"time\":2462,\"level\":23}]},{\"account_id\":4294967295,\"player_slot\":131,\"hero_id\":31,\"item_0\":79,\"item_1\":214,\"item_2\":108,\"item_3\":0,\"item_4\":46,\"item_5\":0,\"kills\":7,\"deaths\":6,\"assists\":6,\"leaver_status\":0,\"gold\":1791,\"last_hits\":63,\"denies\":2,\"gold_per_min\":299,\"xp_per_min\":430,\"gold_spent\":8716,\"hero_damage\":9625,\"tower_damage\":791,\"hero_healing\":569,\"level\":17,\"ability_upgrades\":[{\"ability\":5134,\"time\":165,\"level\":1},{\"ability\":5135,\"time\":318,\"level\":2},{\"ability\":5134,\"time\":338,\"level\":3},{\"ability\":5136,\"time\":394,\"level\":4},{\"ability\":5134,\"time\":506,\"level\":5},{\"ability\":5137,\"time\":569,\"level\":6},{\"ability\":5136,\"time\":604,\"level\":7},{\"ability\":5134,\"time\":680,\"level\":8},{\"ability\":5136,\"time\":857,\"level\":9},{\"ability\":5136,\"time\":1023,\"level\":10},{\"ability\":5137,\"time\":1043,\"level\":11},{\"ability\":5135,\"time\":1226,\"level\":12},{\"ability\":5135,\"time\":1319,\"level\":13},{\"ability\":5135,\"time\":1501,\"level\":14},{\"ability\":5002,\"time\":1749,\"level\":15},{\"ability\":5137,\"time\":2116,\"level\":16},{\"ability\":5002,\"time\":2143,\"level\":17}]},{\"account_id\":110928105,\"player_slot\":132,\"hero_id\":49,\"item_0\":152,\"item_1\":154,\"item_2\":112,\"item_3\":36,\"item_4\":63,\"item_5\":46,\"kills\":17,\"deaths\":4,\"assists\":15,\"leaver_status\":0,\"gold\":5225,\"last_hits\":153,\"denies\":9,\"gold_per_min\":550,\"xp_per_min\":856,\"gold_spent\":16389,\"hero_damage\":24287,\"tower_damage\":2961,\"hero_healing\":0,\"level\":25,\"ability_upgrades\":[{\"ability\":5228,\"time\":170,\"level\":1},{\"ability\":5226,\"time\":260,\"level\":2},{\"ability\":5226,\"time\":300,\"level\":3},{\"ability\":5228,\"time\":358,\"level\":4},{\"ability\":5228,\"time\":431,\"level\":5},{\"ability\":5229,\"time\":471,\"level\":6},{\"ability\":5227,\"time\":525,\"level\":7},{\"ability\":5226,\"time\":555,\"level\":8},{\"ability\":5227,\"time\":668,\"level\":9},{\"ability\":5228,\"time\":697,\"level\":10},{\"ability\":5229,\"time\":786,\"level\":11},{\"ability\":5226,\"time\":1125,\"level\":12},{\"ability\":5227,\"time\":1182,\"level\":13},{\"ability\":5227,\"time\":1248,\"level\":14},{\"ability\":5002,\"time\":1296,\"level\":15},{\"ability\":5229,\"time\":1368,\"level\":16},{\"ability\":5002,\"time\":1577,\"level\":17},{\"ability\":5002,\"time\":1712,\"level\":18},{\"ability\":5002,\"time\":1859,\"level\":19},{\"ability\":5002,\"time\":1936,\"level\":20},{\"ability\":5002,\"time\":2111,\"level\":21},{\"ability\":5002,\"time\":2276,\"level\":22},{\"ability\":5002,\"time\":2331,\"level\":23},{\"ability\":5002,\"time\":2424,\"level\":24},{\"ability\":5002,\"time\":2424,\"level\":25}]}],\"radiant_win\":false,\"duration\":2293,\"start_time\":1381906236,\"match_id\":346805844,\"match_seq_num\":316035716,\"tower_status_radiant\":4,\"tower_status_dire\":1846,\"barracks_status_radiant\":3,\"barracks_status_dire\":63,\"cluster\":151,\"first_blood_time\":112,\"lobby_type\":0,\"human_players\":10,\"leagueid\":0,\"positive_votes\":0,\"negative_votes\":0,\"game_mode\":1}}"); JSONArray players = result.optJSONArray("players"); Player player; String data = null; for (int i = 0; i < players.length(); i++) { player = new Player(players.getJSONObject(i)); data += player.getFormattedHero(); } display.setText(data); assuming i have this code on my project. i am wondering what is the problem on this code. if any of you can help me i would be very glad. click here to view the formatted json string.
in current json string players is an JSONArray which is inside result JSONObject so you will need to first get result JSONObject from main JSONObject then get players JSONArray from it as: JSONObject result = new JSONObject(<JSON_STRING_HERE>); // get result JSONObject JSONObject jsonobj_result = result.optJSONObject("result"); // get players JSONArray JSONArray players = jsonobj_result.optJSONArray("players"); Player player; String data = null; for (int i = 0; i < players.length(); i++) { player = new Player(players.getJSONObject(i)); data += player.getFormattedHero(); }
String data = null; replaced by StringBuffer data = new StringBuffer(); may better.
JSONObject result; URL url = new URL( ""); URLConnection openConnection = url.openConnection(); openConnection.connect(); InputStream inputStream = openConnection.getInputStream(); String inputStream2String = inputStream2String(inputStream); result = new JSONObject(inputStream2String); // here is my add code // you can look the all names in the thi jsonObject JSONArray names = result.names();// no hava players name in // here; so String string = result.getString("result"); result = new JSONObject(string); // my add code end // look names again names = result.names();// hava players name so get // optJSONArray for players JSONArray players = result.optJSONArray("players");// getData is ok
Android JSON parse troubles
I have a web service returning the following string verbatim: "{\"type\":\"youtube\", \"data\":\"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk\",\"pixel_id\":\"471\",\"x\":\"12\",\"y\":\"14\",\"pid\":\"4\",\"surface_id\":\"7\",\"data_id\":\"7224\",\"user_id\":\"4\"}" Code looks lke: dataScanner.client = new DefaultHttpClient(); dataScanner.post = new HttpPost("http://someurl/somepage.php"); post.setEntity(new UrlEncodedFormEntity(userKV)); Log.d("DST Scanner", "post string:" + post.toString()); HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line); } Log.d("DST Scanner", "Post Response (string)" + builder.toString()); //JSONTokener tokener = new JSONTokener(builder.toString()); finalResult = new JSONObject(builder.toString()); I've tried many different formats (escaped quotes, unescaped quotes, no surrounding quotes, escaped forward slashes), but I keep getting this error: org.json.JSONException: Value {"type":"youtube", "data":"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk","pixel_id":"471","x":"12","y":"14","pid":"4","surface_id":"7","data_id":"7224","user_id":"4"} of type java.lang.String cannot be converted to JSONObject Everything looks fine to me, but I've been looking at this so long I wouldn't be surprised if there's some silly thing I'm doing..
I'm new to json, but all of my JSON start and end with "[" and "]" and I use PHP to echo out the json_encode method. On Android side i use: try { URL pHH = new URL("http://192.168.1.5/somephp.php"); URLConnection WC = pHH.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(WC.getInputStream())); String line; while((line = in.readLine()) != null){ JSONArray ja = new JSONArray(line); for (int i = 0; i < ja.length(); i++){ JSONObject jo = (JSONObject) ja.get(i); items[i] = jo.getString("title"); thumbnails[i] = jo.getString("thumb"); links[i] = jo.getString("link"); } }
char[] utf8 = null; StringBuilder properString = new StringBuilder(""); utf8 = Response.toCharArray(); for (int i = 0; i < utf8.length; i++) { if ((int) utf8[i] < 65000) { properString.append(utf8[i]); } } System.out.println("Response of Login::" + properString.toString());