Search code examples
androidinterfaceandroid-asynctaskgoogle-maps-api-2

Google Maps API to get JSON data and set it as info window


I have a somehow long question. I am now learning about Google Maps API and I am required to make the app get some JSON data from a website, then set some of this data in an info window as the title or whatever. The important part is that I have to do this with an interface class, whereas the AsyncTask that downloads this data must also be in another class. So I am currently very confused how to make this communication possible, and to have as little code as possible in the AsyncTask class. I also don't understand very well this interface thing. Please someone help. So here is the main activity:

package com.example.gmapsexample;

public class MainActivity extends Activity {

    private GoogleMap mMap;
    Marker marker = null;
    HttpClient klient;
    String data;
    String s;
    Double latt, lngg;
    GoogleMapOptions options;
    String adres = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=en&username=sartheris";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        options = new GoogleMapOptions();
        mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        options.mapType(GoogleMap.MAP_TYPE_SATELLITE).compassEnabled(true).rotateGesturesEnabled(true).tiltGesturesEnabled(true).zoomControlsEnabled(true);

        klient = new DefaultHttpClient();

        GetJson gg = new GetJson();
        gg.execute();

        /** On Info Window Click */
        mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                marker.setTitle(s);
                Toast.makeText(getApplicationContext(), "Info Window Clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Here is the GetJson class

package com.example.gmapsexample;

public class GetJson extends AsyncTask<String, Void, String> {

    HttpClient klient;
    String adres = "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=en&username=sartheris";
    String s;
    Double latt, lngg;
    private GoogleMap mMap;
    Marker marker;
    GoogleMapOptions options;

    @Override
    protected String doInBackground(String... params) {
        klient = new DefaultHttpClient();
        options = new GoogleMapOptions();
        StringBuilder url = new StringBuilder(adres);
        HttpGet hg = new HttpGet(url.toString());
        HttpResponse hr = null;
        try {
            hr = klient.execute(hg);
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        int status = hr.getStatusLine().getStatusCode();
        if (status == 200) {
            HttpEntity he = hr.getEntity();
            String data = null;
            try {
                data = EntityUtils.toString(he);
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONObject jsonGet = null;
            try {
                jsonGet = new JSONObject(data);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            if (jsonGet.has("geonames")) {
                try {
                    JSONObject arrGet = jsonGet.getJSONArray("geonames").getJSONObject(0);
                    s = arrGet.getString("toponymName");
                    latt = arrGet.getDouble("lat");
                    lngg = arrGet.getDouble("lng");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        marker = new Marker(this);
        marker = mMap.addMarker(new MarkerOptions()
        .position(new LatLng(latt, lngg))
        .title("HELLO WORLD").snippet("BLQ")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                        .draggable(true));
    }
}

And now I need an interface class that would help with the data passing...


Solution

  • In your main class create an interface:

    public interface ParsingCallback{
    
        void onFinishedParsing(MarkerOptions marker);
    }
    

    Pass it a copy to your AsyncTask

    GetJson gg = new GetJson(new ParsingCallback(){
        void onFinishedParsing(MarkerOptions marker) {
             mMap.addMarker(marker);
        }     
    );
    gg.execute();
    

    In your AsyncTask create the constructor

    private ParsingCallback _callback;
    
    public GetJson (ParsingCallback callback){
         _callback = callback;
    }
    

    And then in your onPostExecute:

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    
    
        _callback.onFinishedParsing(new MarkerOptions()
             .position(new LatLng(latt, lngg))
             .title("HELLO WORLD")
             .snippet("BLQ")
        );
    }
    

    Hope that helps :)