如果互联网在 android 中途中断,应用程序会崩溃

App Crashing if the internet goes off in mid in android

我正在我的 android 应用程序中获取 json 模式,它工作正常。但问题是,如果在获取数据的过程中互联网中断,应用程序就会崩溃。我该如何处理这个异常?

我正在调用 new LoadPlaces().execute();,然后在 doInBackground 方法中调用 googlePlaces.search(lat1, lon1, radius, types);,它获取 json 数据并将其分配给一个对象。

这是搜索方式

public PlacesList search(double latitude, double longitude, double radius, String types)
        throws Exception {

    this._latitude = latitude;
    this._longitude = longitude;
    this._radius = radius;

    try {

        HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
        HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
        request.getUrl().put("key", API_KEY);
        request.getUrl().put("location", _latitude + "," + _longitude);
        request.getUrl().put("radius", _radius);                            // in meters
        request.getUrl().put("sensor", "false");
        if(types != null)
            request.getUrl().put("types", types);

        PlacesList list = request.execute().parseAs(PlacesList.class);
        // Check log cat for places response status
        Log.d("Places Status", "" + list.status);
        return list;

    } catch (HttpResponseException e) {
        Log.e("Error:", e.getMessage());
        return null;
    }
}

请回复并帮助我,这对我来说至关重要。我准备提供赏金,但请帮助我。谢谢

Logcat

06-08 05:15:25.335  32008-32008/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.atifarain.customizedcamera, PID: 32008
java.lang.NullPointerException
        at com.example.atifarain.customizedcamera.MainActivity$LoadPlaces.run(MainActivity.java:485)
        at android.app.Activity.runOnUiThread(Activity.java:4757)
        at com.example.atifarain.customizedcamera.MainActivity$LoadPlaces.onPostExecute(MainActivity.java:479)
        at com.example.atifarain.customizedcamera.MainActivity$LoadPlaces.onPostExecute(MainActivity.java:446)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access0(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5105)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
        at dalvik.system.NativeStart.main(Native Method)

MainActivity

class LoadPlaces extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(String... args) {
        // creating Places class object
        googlePlaces = new GooglePlaces();

        try {
            // Separeate your place types by PIPE symbol "|"
            // If you want all types places make it as null
            //String types = "establishment|art_gallery|museum|place_of_worship";
            //String types = "art_gallery|museum";
            String types = "art_gallery|museum|place_of_worship";
            double radius = 1000;       // 1000 meters
            // get nearest places
            nearPlaces = googlePlaces.search(lat1, lon1, radius, types);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Always use runOnUiThread(new Runnable()) to update UI from background
     * thread, otherwise you will get error
     * **/
    protected void onPostExecute(String file_url) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed Places into LISTVIEW
                 * */
                // Get json response status
                String status = nearPlaces.status;

                // Check for all possible status
                if(status.equals("OK")){
                    // Successfully got places details
                    if (nearPlaces.results != null) {
                        // loop through each place
                        ArrayList<String> coordinates = new ArrayList<String>();
                        ArrayList<Double> bearings = new ArrayList<Double>();

                        for (NearbyPlaceNodes p : nearPlaces.results) {
                            HashMap<String, String> map = new HashMap<String, String>();

                            // NearbyPlaceNodes reference is used to get "place full details"
                            map.put(KEY_REFERENCE, p.reference);
                            map.put(KEY_NAME, p.name);          // NearbyPlaceNodes name

                            double lat2 = p.geometry.location.lat;
                            double lon2 = p.geometry.location.lng;

                            double _bearing = bearing(lat1, lon1, lat2, lon2);
                            bearings.add(_bearing);

                            String lat = Double.toString(lat2);
                            String lon = Double.toString(lon2);
                            String latlon = lat+","+lon;

                            coordinates.add(latlon);
                            String bearing_ = String.format("%.04f",_bearing);

                            String nearbyDat = latlon+","+bearing_+","+p.name;
                            nearbyData.add(nearbyDat);

                            placesListItems.add(map);       // adding HashMap to ArrayList
                        }

                        MainActivity.this.onBackgroundTaskDataObtained(nearbyData);
                    }
                }

第 485 行 => String status = nearPlaces.status;

第 479 行 => runOnUiThread(new Runnable() {

第 446 行 => class LoadPlaces extends AsyncTask<String, String, String> {

您的 search 方法中间的网络故障似乎会触发将在此处捕获的异常:

catch (HttpResponseException e) {
        Log.e("Error:", e.getMessage());
        return null;
    }

你 return null,将在你的 doInBackground 方法上分配给 nearPlaces:

nearPlaces = googlePlaces.search(lat1, lon1, radius, types);

因此,在 onPostExecute 方法中,变量 nearPlaces 为空,您正试图访问空变量上的字段:

String status = nearPlaces.status;

导致您在日志中看到的崩溃。简单快捷的解决方案是在对 onPostExecute 执行任何操作之前检查 nearPlaces 是否为 null,并且可能会显示一条错误消息。

顺便说一下,在 onPostExecute 上这样做是多余的:

runOnUiThread(new Runnable() {
 public void run() { ... }
})

onPreExecuteonPostExecute 总是默认在 UI 线程上调用,这是 AsyncTask.

存在的主要原因