0

Im trying to download Latitude and longitude data from my database, and create map markers in android for them. However i am receiving an error

05-25 18:54:33.834: E/ExampleApp(4893): Error processing JSON
05-25 18:54:33.834: E/ExampleApp(4893): org.json.JSONException: Value 51.9111546,4.477839 at latlng of type java.lang.String cannot be converted to JSONArray
05-25 18:54:33.834: E/ExampleApp(4893):     at org.json.JSON.typeMismatch(JSON.java:100)
05-25 18:54:33.834: E/ExampleApp(4893):     at org.json.JSONObject.getJSONArray(JSONObject.java:553)
05-25 18:54:33.834: E/ExampleApp(4893):     at info.androidhive.jsonparsen.mapview.createMarkersFromJson(mapview.java:117)
05-25 18:54:33.834: E/ExampleApp(4893):     at info.androidhive.jsonparsen.mapview$2.run(mapview.java:99)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.os.Handler.handleCallback(Handler.java:733)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.os.Handler.dispatchMessage(Handler.java:95)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.os.Looper.loop(Looper.java:136)
05-25 18:54:33.834: E/ExampleApp(4893):     at android.app.ActivityThread.main(ActivityThread.java:5103)
05-25 18:54:33.834: E/ExampleApp(4893):     at java.lang.reflect.Method.invokeNative(Native Method)
05-25 18:54:33.834: E/ExampleApp(4893):     at java.lang.reflect.Method.invoke(Method.java:515)
05-25 18:54:33.834: E/ExampleApp(4893):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
05-25 18:54:33.834: E/ExampleApp(4893):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
05-25 18:54:33.834: E/ExampleApp(4893):     at dalvik.system.NativeStart.main(Native Method)

I cannot seem to find how to fix this

Here is my activity code (apart from some SetUpMap methods).

protected void retrieveAndAddCities() throws IOException {
    HttpURLConnection conn = null;
    final StringBuilder json = new StringBuilder();
    try {
        // Connect to the web service
        URL url = new URL(SERVICE_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            json.append(buff, 0, read);
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        throw new IOException("Error connecting to service", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // Create markers for the city data.
    // Must run this on the UI thread since it's a UI operation.
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                createMarkersFromJson(json.toString());
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }
        }
    });
}

void createMarkersFromJson(String json) throws JSONException {
    // De-serialize the JSON string into an array of city objects
    JSONArray jsonArray = new JSONArray(json);
    for (int i = 0; i < jsonArray.length(); i++) {
        // Create a marker for each city in the JSON data.
        JSONObject jsonObj = jsonArray.getJSONObject(i);
        map.addMarker(new MarkerOptions()
            .title(jsonObj.getString("name"))
            .snippet(Integer.toString(jsonObj.getInt("population")))
            .position(new LatLng(
                    jsonObj.getJSONArray("latlng").getDouble(0),
                    jsonObj.getJSONArray("latlng").getDouble(1)
             ))
        );
    }
}
}

the JSON responce

[{"name":"AlbertHeijn","latlng":"51.9111546,4.477839","population":"1234"},{"name":"Jumbo","latlng":"51.9054127,4.4960587","population":"23"}]

I am using the json_encode($resultarray) to show my JSON on the website.

any detailed explanation wil be greatly appreciated.

user3671459
  • 455
  • 3
  • 8
  • 21
  • you need to show your json response from php !!!! – Pankaj May 25 '14 at 17:09
  • I have edited my post and added the JSON response. I have also checked with a JSON validator if it is correct JSON and it was. – user3671459 May 25 '14 at 17:11
  • you are storing latlong as string and fetching as JsonArray.for the same jsonobject fetch it with getString. – Pankaj May 25 '14 at 17:15
  • I think you're not declaring the latitude and longitude values as an array. Also, I'd suggest using the gson library. – arielnmz May 25 '14 at 17:16
  • @Pankaj i know, thats where the problem is, it should be de-serialized to a Array... – user3671459 May 25 '14 at 17:19
  • dude latlong will return a string type.or else store it as a double or use GIS system to store latlong in mysql – Pankaj May 25 '14 at 17:22
  • @Pankaj i know it does, that doesn't help me. the problem is it cannot convert, and i have no options on the database side. – user3671459 May 25 '14 at 17:34

3 Answers3

0

The value corresponding to "latlng" in your JSON is a string and not an array. Therefore jsonObj.getJSONArray("latlng") won't work.

I see two solutions to your issue:

  • you extract the string with jsonObj.getString("latlng"), split it around the comma, and convert to double the two values.

    JSONObject jsonObj = jsonArray.getJSONObject(i);
    string s = jsonObj.getString("latlng"); // "51.9111546,4.477839";
    string[] lat_long = s.Split(',');
    map.addMarker(new MarkerOptions()
            .title(jsonObj.getString("name"))
            .snippet(Integer.toString(jsonObj.getInt("population")))
            .position(new LatLong(
                    Convert.ToDouble(lat_long[0]),
                    Convert.ToDouble(lat_long[1])))
            );
    
  • you modify your JSON to contain an array for the "latlong" value and extract it (code below JSON)

[
    {
        "name": "AlbertHeijn",
        "latlng": {
            "lat": "51.9111546",
            "long": "4.477839"
        },
        "population": "1234"
    },
    {
        "name": "Jumbo",
        "latlng": {
            "lat": "51.9054127",
            "long": "4.4960587"
        },
        "population": "23"
    }
]

code:

JSONObject location = object.getJSONObject("latlng");
[...]
.position(new LatLng(
                   location.getString("lng"),
                   location.getString("lat")
             ))

Concerning this last bit, I used location.getString() because your original JSON is built using strings for the latitude and longitude values... to use getDouble(), you should remove the quotes around those values, i.e:

 "latlng": {
                "lat": 51.9054127,
                "long": 4.4960587
            },
Slyvain
  • 1,732
  • 3
  • 23
  • 27
  • i believe your first answer is the most convenient if you use googlemaps to get the latitude and longitude as they show it as '51.503304,4.60303' so it wil automatically split that, your second one however is what i used, as it seems more clear. – user3671459 May 27 '14 at 09:37
0

check my answer on How to decode JSON values in my Android Aplication?

This will help you. You may want to use FORCE_OBJECT or json_encode("data", $yourarray)

Community
  • 1
  • 1
Emanuel
  • 8,027
  • 2
  • 37
  • 56
0

Get the latlong from

getString

and then use split by delimeter and extract both the values of lat and long and store it in two variables and use them.

Soumil Deshpande
  • 1,622
  • 12
  • 14