没有得到JSON数据到图形页面,只获得空白地图

编程入门 行业动态 更新时间:2024-10-22 23:48:16
本文介绍了没有得到JSON数据到图形页面,只获得空白地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述   

可能重复:结果  android.os.NetworkOnMainThreadException

我正在获取JSON数据转换成图形页面显示的位置,但每当我运行我的程序没有得到数据转换成地图刚开空白地图,而JSON数据,这里我把我的JSON数据和活动code,请告诉我在这里我做的错误    {    地图:[    {

头衔:广场一号,纬度:46.483742经度:7.663157,国:瑞士},{头衔:将两个纬度:59.25235经度:18.465536,国:瑞典},{头衔:广场三座纬度:56.404182经度:-3.818855,国:苏格兰}]}

活动code: -

公共类主要扩展MapActivity {公众的GeoPoint点;TapControlledMapView图形页面; //使用自定义TapControlledMapView清单<&叠加GT; mapOverlays;可绘制可绘制;SimpleItemizedOverlay itemizedOverlay;@覆盖公共无效的onCreate(最终捆绑savedInstanceState){    super.onCreate(savedInstanceState);    的setContentView(R.layout.main);    图形页面=(TapControlledMapView)findViewById(R.id.mapview);    mapView.setBuiltInZoomControls(真);    mapView.setSatellite(假);    //在图形页面的单一的水龙头解雇气球(iOS的行为)    mapView.setOnSingleTapListener(新OnSingleTapListener(){        公共布尔onSingleTap(MotionEvent五){            itemizedOverlay.hideAllBalloons();            返回true;        }    });    mapOverlays =调用MapView.getOverlays();    绘制= getResources()getDrawable(R.drawable.ic_launcher)。    itemizedOverlay =新SimpleItemizedOverlay            (绘制,图形页面);    itemizedOverlay.setShowClose(假);    itemizedOverlay.setShowDisclosure(真);    itemizedOverlay.setSnapToCenter(假);     类DownloadWebPageTask扩展的AsyncTask<弦乐,太虚,字符串> {        @覆盖        保护字符串doInBackground(字符串的URL ...){    HttpClient的客户端=新DefaultHttpClient();    //执行一个JSON列表的GET请求    HttpUriRequest要求=新HTTPGET            (https://开头DL !!!!的 / maps.json。);    //获取发送回响应    HTT presponse响应= NULL;    尝试{        响应= client.execute(请求);    }赶上(ClientProtocolException E1){        // TODO自动生成catch块        e1.printStackTrace();    }赶上(IOException异常E1){        // TODO自动生成catch块        e1.printStackTrace();    }    //转换这种反应成可读的字符串    字符串jsonString = NULL;    尝试{        jsonString = StreamUtils.convertToString                (response.getEntity()的getContent());    }赶上(E1 IllegalStateException异常){        // TODO自动生成catch块        e1.printStackTrace();    }赶上(IOException异常E1){        // TODO自动生成catch块        e1.printStackTrace();    }    //创建我们可以从字符串使用JSON对象    JSONObject的JSON = NULL;    尝试{        JSON =新的JSONObject(jsonString);    }赶上(JSONException E1){        // TODO自动生成catch块        e1.printStackTrace();    }               尝试{     JSONArray jsonArray = json.getJSONArray(地图);     Log.e(log_tag,打开JSON阵列);        的for(int i = 0; I< jsonArray.length();我++)            {            的JSONObject的JSONObject = jsonArray.getJSONObject(I)                字符串纬度= jsonObject.getString(纬度);                串经度= jsonObject.getString(经度);                字符串title = jsonObject.getString(标题);                字符串国家= jsonObject.getString(国家);                双纬度= Double.parseDouble(纬度);                双LNG = Double.parseDouble(经度);                     Log.e(log_tag,添加的GeoPoint+称号);                      点=新的GeoPoint(                             (INT)(LAT * 1E6)                             (INT)(LNG * 1E6));                    OverlayItem overlayItem =新OverlayItem(点,标题,                            国家);                    itemizedOverlay.addOverlay(overlayItem);                    }               }赶上(JSONException E){                 Log.e(log_tag,错误分析数据+ e.toString());            }               itemizedOverlay.populateNow();               mapOverlays.add(itemizedOverlay);                    如果(savedInstanceState == NULL){            MapController控制器= mapView.getController();                        controller.setCenter(点);                        controller.setZoom(7);                    }其他{              //例如恢复覆盖的聚焦状态                        INT重点;                聚焦= savedInstanceState.getInt(focused_1,-1);            如果(聚焦> = 0){                              itemizedOverlay.setFocus                       (itemizedOverlay.getItem(聚焦));                        }                    }                    返回jsonString; }     }     }

解决方案

例外说,所有:尝试通过加载UI线程里面的地图做了一个网络操作。这是一个坏主意,因为网络接入是缓慢的,在运行时会阻止用户界面。

您应该移动地图加载到一个不同的线程例如通过使用的AsyncTask 。基本上你定义扩展的AsyncTask A类,然后运行下载的 doInBackground(),并将结果填入到视图在 onPostExecute()。请参阅的Andr​​oid文档以获取更多信息。

在你的情况,你需要把这个code座到 doInBackground()方法:

HttpClient的客户端=新DefaultHttpClient();//执行一个JSON列表的GET请求HttpUriRequest要求=新HTTPGET(HTTPS://dl.###/maps.json);//获取发送回响应HTT presponse响应= NULL;尝试{    响应= client.execute(请求);}赶上(ClientProtocolException E1){    // TODO自动生成catch块    e1.printStackTrace();}赶上(IOException异常E1){    // TODO自动生成catch块    e1.printStackTrace();}//创建我们可以从字符串使用JSON对象JSONObject的JSON = NULL;尝试{    JSON =新的JSONObject(jsonString);}赶上(JSONException E1){    // TODO自动生成catch块    e1.printStackTrace();}

和确保其返回进一步处理 JSON 对象(基本上是按照code线)在 onPostExecute()

有一个看文档的一个例子。您还可以看看这code 更多的例子。

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 ("dl.!!!!/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; } } }

解决方案

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("dl.###/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.

更多推荐

没有得到JSON数据到图形页面,只获得空白地图

本文发布于:2023-07-19 08:53:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图形   空白   页面   地图   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!