0

i'm working on an app that uses JSON Responses which has both JSONObject and JSONArray. Both the information are required to place markers on map. But i'm facing problem in parsing both.

This is my Response when I called my URl

{
-source: {
LS: " ABCDEF",
name: "XYXA",
point: "77.583859,12.928751"
},
 -stores: [
    -{
    ph: null,
    distance: "0.3",
    LS: " abcd",
    id: 1209,
    name: "xyz",
    point: "77.583835,12.926359"
    },
-{
    ph: null,
    distance: "0.3",
    LS: " abcd",
    id: 1209,
    name: "xyz",
    point: "77.583835,12.926359"
    }
    ]
}

This is how I tried to handle JSON response

public class JSONResponseHandler implements ResponseHandler<List<LatlongRec>> {
        @Override
        public List<LatlongRec> handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            List<LatlongRec> result = new ArrayList<LatlongRec>();
            String JSONResponse = new BasicResponseHandler()
                    .handleResponse(response);


            try {

                JSONObject object = (JSONObject)new JSONTokener(JSONResponse)
                        .nextValue();

                JSONArray stores = object.getJSONArray("stores");
                for (int i = 0; i < stores.length(); i++) {
                    JSONObject tmp = (JSONObject) stores.get(i);
                    result.add(new LatlongRec(tmp.getString("point"), tmp
                            .getString("name"), tmp.getString("LS"), tmp
                            .getString("ph")));
                    Log.v("points", "" + tmp.getString("point"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return result;
        }
    }

In this LatlongRec is a class where I have created constructor and getters.

This is my Main Activity

public class SecondActivity extends Activity {
    private static final double CAMERA_LNG = 77.583859;
    private static final double CAMERA_LAT = 12.928751;
    // The Map Object
    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        String city = getIntent().getStringExtra("city");
        String area1 = getIntent().getStringExtra("area");
        String area = area1.trim();

        String URL = "http://xyzxyz.search.json?query="
                + area + "&city=" + city + "&app_id=test";
        new HttpGetTask().execute(URL);
    }

    private class HttpGetTask extends AsyncTask<String, Void, List<LatlongRec>> {
        AndroidHttpClient mClient = AndroidHttpClient.newInstance("");

        @Override
        protected List<LatlongRec> doInBackground(String... params) {
            HttpGet request = new HttpGet(params[0]);
            JSONResponseHandler responseHandler = new JSONResponseHandler();
            try {

                return mClient.execute(request, responseHandler);
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }
            return null;
        }

        @SuppressLint("NewApi")
        protected void onPostExecute(List<LatlongRec> result) {
            // Get Map Object
            mMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();
            if (null != mMap) {
                // Add a marker for every earthquake
                for (final LatlongRec rec : result) {
                    Log.v("pointM", "" + rec.getPoint());
                    Log.v("NAMES", "" + rec.getName());

                    String point = rec.getPoint();
                    String[] latlng = point.split(",");
                    String lat = latlng[0];
                    String lng = latlng[1];

                    Double lat1 = Double.parseDouble(lat);
                    Double lng1 = Double.parseDouble(lng);



                    Log.v("LATLNGM", "lat" + lng + "& lng " + lat);
                    // Add a new marker for each point
                    mMap.addMarker(new MarkerOptions()
                            .position(new LatLng(lng1, lat1))
                            .title(rec.getName())
                            .snippet(rec.getLS() + rec.getPh())
                            .icon(BitmapDescriptorFactory
                                    .fromResource(R.drawable.main_marker)));
                // Setting a custom info window adapter for the google map
                CameraPosition cp = new CameraPosition(new LatLng(CAMERA_LAT,
                        CAMERA_LNG), 15, 40, 90);
                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
            }
            if (null != mClient)
                mClient.close();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }
}

How to get points in source object to my main activity so that i can set CAMERA_LAT and CAMERA_LNG to Lat and Lng from that point.?

I'm new to JSON please help me to solve this.

Thanking you

vzamanillo
  • 9,905
  • 1
  • 36
  • 56
rubin
  • 271
  • 2
  • 6
  • 14

2 Answers2

2
String point[] = jsonObject.getJSONObject("source").getString("point").split(",");
double lat = Double.parseDouble(point[0]);
double lon = Double.parseDouble(point[1]);

Should get you on your way to getting the points out.

If you are looking on getting them to another activity, you should put them into a Bundle and pass them to the next activity. Here is a post explaining how to pass a bundle.

Community
  • 1
  • 1
nathansizemore
  • 3,028
  • 7
  • 39
  • 63
  • Thanks now i'm getting points in my log. How to set these points to my main activities CAMERA_LAT and CAMERA_LNG..? – rubin Apr 01 '14 at 18:09
  • @dharshan Is this in a separate activity, or all inside one activity? – nathansizemore Apr 01 '14 at 18:10
  • yes for my clarity i divided whole program into a separate JSONResponseHandler class to handle JSON responses and accessed in my main activity through a LatlongRec class – rubin Apr 01 '14 at 18:14
  • @dharshan Inside your `onPostExecute` function, assign the values to `CAMERA_LNG` and `CAMERA_LAT`. Because `HttpGetTask` is a sub-class of your MainActivity, it has access to those properties – nathansizemore Apr 01 '14 at 18:27
  • its getting null values when i initialize values in onPostExecute – rubin Apr 01 '14 at 18:43
  • @dharshan Log all the values every step of the way in the process to LogCat. This will help you figure out when they go to `null`. – nathansizemore Apr 01 '14 at 18:57
0

Try out a deserializer. I used the google GSON library to solve a similar problem I had. Take a peek at how I parsed the heroes array in the json object.

public class GameDeserializer implements JsonDeserializer<Game> {

    public Game deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        JsonObject obj = json.getAsJsonObject().get("game").getAsJsonObject();

        String id = obj.get("id").getAsString();
        Integer turn = obj.get("turn").getAsInt();
        Integer maxTurns = obj.get("maxTurns").getAsInt();

        Hero[] heroes = new Hero[4];
        for (int i = 0; i < 4; i++) {
            heroes[i] = context.deserialize(obj.get("heroes").getAsJsonArray().get(i), Hero.class);
        }
        Board board = context.deserialize(obj.get("board"), Board.class);

        Hero player = context.deserialize(json.getAsJsonObject().get("hero"), Hero.class);

        String token = json.getAsJsonObject().get("token").getAsString();

        String viewUrl = json.getAsJsonObject().get("viewUrl").getAsString();

        String playUrl = json.getAsJsonObject().get("playUrl").getAsString();

        boolean finished = obj.get("finished").getAsBoolean();

        return new Game(id, turn, maxTurns, heroes, board, player, token, viewUrl, playUrl, finished);
    }

}
}

I wouldn't have answered, but your question is very ambiguous and I'm not exactly sure if you need help with json, or with a String. In the latter case, disregard my answer.

Aarowaim
  • 801
  • 4
  • 10