引起:java.lang.NullPointerException,不幸的是应用程序停止了

时间:2012-10-27 06:15:24

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

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

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:1)

您是否阅读过this

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

onPostExecute()方法执行UIThread

后,doInBanckground()方法执行doInBackground

onPostExecute中执行某项任务后需要查看的更改必须写在doInBackground中,例如,如果您在ProgressDialog中执行某些网络服务操作,则可以使用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)); } } } } 刚试过它..

{{1}}

答案 2 :(得分:0)

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