0

Possible Duplicate:
android.os.NetworkOnMainThreadException

i am fetching JSON data into MapView to show locations, but whenever i run my program not getting data into Map just getting blank map without json data, here i am placing my json data and Activity Code, please tell me where i am doing mistake { "maps": [ {

"title": "Place One",
"latitude" : "46.483742",
"longitude" : "7.663157",
"country": "Switzerland"
},
{
"title" : "Place Two",
"latitude" : "59.25235",
"longitude" : "18.465536",
"country" : "Sweden"
},
{
"title" : "Place Three",
"latitude" : "56.404182",
"longitude" : "-3.818855",
"country" : "Scotland"
}
]
}

Activity Code:-

public class Main extends MapActivity {
public GeoPoint point;
TapControlledMapView mapView; // use the custom TapControlledMapView
List<Overlay> mapOverlays;
Drawable drawable;
SimpleItemizedOverlay itemizedOverlay;

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mapView = (TapControlledMapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setSatellite(false);
    // dismiss balloon upon single tap of MapView (iOS behavior) 
    mapView.setOnSingleTapListener(new OnSingleTapListener() {      
        public boolean onSingleTap(MotionEvent e) {
            itemizedOverlay.hideAllBalloons();
            return true;

        }
    });

    mapOverlays = mapView.getOverlays();        
    drawable = getResources().getDrawable(R.drawable.ic_launcher);
    itemizedOverlay = new SimpleItemizedOverlay
            (drawable, mapView);        
    itemizedOverlay.setShowClose(false);
    itemizedOverlay.setShowDisclosure(true);
    itemizedOverlay.setSnapToCenter(false);

     class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

    HttpClient client = new DefaultHttpClient();
    // Perform a GET request for a JSON list
    HttpUriRequest request = new HttpGet
            ("https://dl.!!!!.com/maps.json");
    // Get the response that sends back
    HttpResponse response = null;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // Convert this response into a readable string
    String jsonString = null;
    try {
        jsonString = StreamUtils.convertToString
                (response.getEntity().getContent());
    } catch (IllegalStateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // Create a JSON object that we can use from the String
    JSONObject json = null;
    try {
        json = new JSONObject(jsonString);
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


               try{

     JSONArray jsonArray = json.getJSONArray("maps");
     Log.e("log_tag", "Opening JSON Array ");
        for(int i=0;i < jsonArray.length();i++)
            {                       

            JSONObject jsonObject = jsonArray.getJSONObject(i);

                String latitude =  jsonObject.getString("latitude");
                String longitude =  jsonObject.getString("longitude");
                String title =  jsonObject.getString("title");
                String country = jsonObject.getString("country");


                double lat = Double.parseDouble(latitude);
                double lng = Double.parseDouble(longitude);


                     Log.e("log_tag", "ADDING GEOPOINT"+title); 

                      point = new GeoPoint(
                             (int) (lat * 1E6), 
                             (int) (lng * 1E6));
                    OverlayItem overlayItem = new OverlayItem(point, title, 
                            country);
                    itemizedOverlay.addOverlay(overlayItem);

                    }
               }catch(JSONException e)        {
                 Log.e("log_tag", "Error parsing data "+e.toString());
            } 

               itemizedOverlay.populateNow(); 

               mapOverlays.add(itemizedOverlay);
                    if (savedInstanceState == null) {
            MapController controller = mapView.getController();
                        controller.setCenter(point);
                        controller.setZoom(7);

                    } else {

              // example restoring focused state of overlays
                        int focused;
                focused = savedInstanceState.getInt("focused_1", -1);
            if (focused >= 0) {
                              itemizedOverlay.setFocus
                       (itemizedOverlay.getItem(focused));
                        }
                    }
                    return jsonString;   }
     }

     }
Community
  • 1
  • 1
Stanley
  • 319
  • 1
  • 2
  • 8
  • could you please tell me where i am missing – Stanley Oct 26 '12 at 08:01
  • 1
    @Stanley Don't write network related task in main UI Thread, use separate thread for network related task. – Dipak Keshariya Oct 26 '12 at 08:09
  • Hi Dipak, thanks for reply but i am confuse where and how i need to write my code, could you please write it for me, please use above code, it would be easy to understand for me, further i will use same way... – Stanley Oct 26 '12 at 08:14
  • what code i need to move in onPostExecute()method, i have tried several but getting errors, could you help me out – Stanley Oct 26 '12 at 09:22

1 Answers1

1

The exception says all: you are trying to do a network operation by loading the maps inside the UI thread. This is a bad idea, as network access is slow and will block the UI while it is running.

You should move the maps loading into a different thread e.g. by using an AsyncTask. Basically you define a class that extends AsyncTask and then runs the download in doInBackground() and fills the result into the view within onPostExecute(). See the Android docs for more information.

In your case you need to put this code block into the doInBackground() method:

HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet("https://dl.###.com/maps.json");
// Get the response that sends back
HttpResponse response = null;
try {
    response = client.execute(request);
} catch (ClientProtocolException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

// Create a JSON object that we can use from the String
JSONObject json = null;
try {
    json = new JSONObject(jsonString);
} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

and make sure that it returns the json object for further processing (basically the lines that follow that code) within onPostExecute()

Have a look at the docs for an example. You can also look at this code for more examples.

Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
  • Heiko, could you please write your idea, by insert my code, where you think it should be, because i don't know what and where to place and write.... – Stanley Oct 26 '12 at 08:18
  • Thanks, i have tried but i still facing problem, could you please write it for me, like you said then i will match my code and able to find the reason or my mistake – Stanley Oct 26 '12 at 08:29
  • Hi Heiko, i have tried your idea, now i am getting Map but without JSON Data, and i did not write any code within postexecute() method, because i am not getting what to write under this one, could you tell me like earlier you helped – Stanley Oct 26 '12 at 08:56
  • Stanley, you need to pass the json object out of `doInBackground` and work on it in the `onPostExecute` method and then populating your map display from within the `onPostExecute` method. – Heiko Rupp Oct 26 '12 at 08:58
  • ok thnx i will try ..... – Stanley Oct 26 '12 at 08:59