没有得到JSON数据到图形页面,只获得空白地图 [英] Not getting json data into mapview, getting blank map only

查看:116
本文介绍了没有得到JSON数据到图形页面,只获得空白地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception\">android.os.NetworkOnMainThreadException


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

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

活动code: -

 公共类主要扩展MapActivity {
公众的GeoPoint点;
TapControlledMapView图形页面; //使用自定义TapControlledMapView
清单&LT;&叠加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&LT;弦乐,太虚,字符串&GT; {
        @覆盖
        保护字符串doInBackground(字符串的URL ...){    HttpClient的客户端=新DefaultHttpClient();
    //执行一个JSON列表的GET请求
    HttpUriRequest要求=新HTTPGET
            (https://开头DL !!!!的.com / 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&LT; 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);
            如果(聚焦&GT; = 0){
                              itemizedOverlay.setFocus
                       (itemizedOverlay.getItem(聚焦));
                        }
                    }
                    返回jsonString; }
     }     }


解决方案

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

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

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

  HttpClient的客户端=新DefaultHttpClient();
//执行一个JSON列表的GET请求
HttpUriRequest要求=新HTTPGET(HTTPS://dl.###.com/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()

有一个看文档的一个例子。您还可以看看<一个href=\"https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/OneTweetActivity.java#L891\"相对=nofollow>这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
            ("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;   }
     }

     }

解决方案

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.

这篇关于没有得到JSON数据到图形页面,只获得空白地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆