没有将json数据导入mapview,只获取空白地图

时间:2012-10-26 07:57:16

标签: android android-mapview

  

可能重复:
  android.os.NetworkOnMainThreadException

我正在将JSON数据提取到MapView中以显示位置,但每当我运行我的程序没有将数据导入Map只是得到没有json数据的空白地图时,我在这里放置我的json数据和活动代码,请告诉我我在哪里做错了     {     “地图”:[     {

"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"
}
]
}

活动代码: -

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;   }
     }

     }

1 个答案:

答案 0 :(得分:1)

异常说明所有:您正在尝试通过在UI线程内加载映射来执行网络操作。这是一个坏主意,因为网络访问速度很慢,并且会在UI运行时阻止它。

您应该将地图加载到不同的线程中,例如使用AsyncTask。 基本上,您定义了一个扩展AsyncTask的类,然后在doInBackground()中运行下载,并将结果填充到onPostExecute()中的视图中。 有关详细信息,请参阅Android docs

在您的情况下,您需要将此代码块放入doInBackground()方法:

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();
}

并确保它在json

中返回onPostExecute()对象以进行进一步处理(基本上是该代码后面的行)

查看文档以获取示例。您还可以查看this code以获取更多示例。