【问题标题】:Caused by: java.lang.NullPointerException, Unfortunately app has stopped原因:java.lang.NullPointerException,不幸的是应用程序已停止
【发布时间】:2012-10-27 06:15:24
【问题描述】:

将 JSON 数据提取到 mapview 中,我仍然在获取地图,但没有地图位置,这是我在 JSON 文件中给出的,并且每当我运行我的应用程序时都会得到这个 - 不幸的是应用程序已经停止并且 Logcat 说:-

 10-27 13:02:18.573: E/AndroidRuntime(719): Caused by: java.lang.NullPointerException
 10-27 13:02:18.573: E/AndroidRuntime(719):     at com.erachnida.restaurant.versionoct.MapView.onCreate(MapView.java:52)

请看下面的代码:-

public class MapView extends MapActivity {
public GeoPoint point;
TapControlledMapView mapView; // use the custom TapControlledMapView
List<Overlay> mapOverlays;
Drawable drawable;
SimpleItemizedOverlay itemizedOverlay;
JSONObject json = null;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

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



        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            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();
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);


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

        }

    }.execute();
}

【问题讨论】:

    标签: android android-emulator android-mapview android-parser


    【解决方案1】:

    AsyncTask 在另一个线程内执行 doInBackground() 中的所有内容,该线程无权访问您的视图所在的 GUI。

    preExecute()postExecute() 为您提供在此新线程中发生繁重工作之前和之后的 GUI 访问权限,您甚至可以将长操作的结果传递给 postExecute() 以显示任何处理结果。

    Here看我的回答。

    尝试跟随它并不完美,但给你一些想法。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    
        mapOverlays = mapView.getOverlays();
        drawable = getResources().getDrawable(R.drawable.ic_launcher);
        itemizedOverlay = new SimpleItemizedOverlay(drawable, mapView);
        itemizedOverlay.setShowClose(false);
        itemizedOverlay.setShowDisclosure(true);
        itemizedOverlay.setSnapToCenter(false);
        new AsyncTask<Void, Void, Void>() {
    
    
    
            @Override
            protected Void doInBackground(Void... params) {
                // TODO Auto-generated method stub
                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();
                }
    
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
    
    
                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));
                    }
                }
    
            }
    
        }.execute();
    }
    

    【讨论】:

    • hardik 谢谢哥们,你能不能用我的代码把它们给我,这样我会更容易理解
    • 你先推荐androidhive.info/2012/01/android-json-parsing-tutorial这个。有问题后告诉我。这是关于您的问题的一个很好的例子。
    • 我已经使用相同的代码来使用 json 解析器,但我很难确切知道需要在 onPostExecute() 方法中移动哪些代码,以及在哪里放置 onPostExecute() 方法,请告诉我兄弟
    • 谢谢我试过,在这一行: JSONArray jsonArray = json.getJSONArray("maps");像以前一样遇到问题,特别是在 getJSONArray
    • 声明 JSONObject json = null;作为全局变量。
    【解决方案2】:

    你读过this吗?

    AsynctaskdoinBackground()方法在Asynctask创建的单独线程中执行,这实际上是为了使任务Async以减少UIThread上的负载

    onPostExecute() 方法确实在UIThread 执行后在doInBanckground() 执行

    doInBackground 中执行某些任务后您需要看到的更改必须写在onPostExecute 中,例如,如果您在doInBackground 中执行一些Web 服务操作,您可能正在使用ProgressDialogdismissing它写在onPostExecute

    或者在你的情况下你有json数组显示数组值必须写在onPostExecute中。

    已编辑 试试这个代码,因为我不确定 mapview 刚刚尝试过..

        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());
               } 
    
    
               return jsonString;
           }
    
               @Override
            protected void onPostExecute(String result) {
     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));
                   }
               }
                  }
    
        }
    

    【讨论】:

    • 请告诉我究竟需要在 onPostExecute 下放置什么代码,这是我之前尝试过但出现很多错误的原因,这就是为什么我也想知道我在哪里犯了愚蠢的错误
    • 需要添加到从json数组获取的地图中的东西需要在onPostExecute方法中。
    • bobbe 我说我试图放置但遇到问题,所以请您使用我的代码向我展示,并且您认为 onPostExecute() 应该看起来像,然后我会找出我错过的地方或者做错了,所以只需要使用我的代码复制和粘贴来显示这些行
    • 我希望你已经调用了这个 Asynctask。就像new DownloadWebPageTask().execute(); 一样,无论它必须被调用
    • 对不起,但我没有我认为这是我没有将 json 数据输入 mapview 的唯一原因,我是对的
    【解决方案3】:

    您没有初始化 TapControlledMapView 对象。初始化它并尝试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2018-03-23
      • 2015-05-09
      • 2016-11-19
      • 2013-09-14
      相关资源
      最近更新 更多