Domanda

Having issues with my AsyncTask when there is no network detected on the device.

Looking for suggestions on how to fix this, thanks.

LogCat seems to point to for (int i = 0; i < json.length(); i++) { and im Unsure how to prevent this code from running if the network is not available

Code


@Override
  protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

        try {
        new ProgressTask(GPSME_Main.this).execute();
        }
        catch(Exception e) {
            Intent callNETWORKSettingIntent = new Intent(
                    android.provider.Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
            startActivity(callNETWORKSettingIntent);
        }
}

Where im parsing location data

 private class ProgressTask extends
        AsyncTask<String, Void, ArrayList<String>> {

    ArrayList<String> arrfortextviews;
    private GPSME_Main activity;
    private ProgressBar progressBar1;

    public ProgressTask(GPSME_Main parseMoreDetails) {
        this.activity = parseMoreDetails;
        context = parseMoreDetails;
        progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);

    }

    private Context context;
    protected void onPreExecute() {
        progressBar1.setVisibility(View.VISIBLE);
        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            parse_current_location = location.getLatitude() + ","
                    + location.getLongitude();
        }
    }

    @Override
    protected void onPostExecute(ArrayList<String> success) {
        if (arrfortextviews.size() > 0) {
            progressBar1.setVisibility(View.GONE);
            current_address = (success.get(0));
            body_location_address_result.setText(current_address);
        }
    }

    protected ArrayList<String> doInBackground(final String... args) {

        JSONParser jParser = new JSONParser();
        arrfortextviews = new ArrayList<String>();

        JSONArray json = jParser.getJSONFromUrl(google_maps_url + "latlng="
                + parse_current_location + "&sensor=true");

        for (int i = 0; i < json.length(); i++) {

            try {
                JSONObject c = json.getJSONObject(i);
                String parsed_results_formatted_address = c
                        .getString("formatted_address");
arrfortextviews.add(parsed_results_formatted_address);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return arrfortextviews;
    }
}

LogCat


: FATAL EXCEPTION: AsyncTask #1
: java.lang.RuntimeException: An error occured while executing doInBackground()
:   at android.os.AsyncTask$3.done(AsyncTask.java:299)
:   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
:   at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
:   at java.util.concurrent.FutureTask.run(FutureTask.java:239)
:   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
:   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
:   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
:   at     java.lang.Thread.run(Thread.java:856)
: Caused by: java.lang.NullPointerException
:   at org.greenbot.technologies.gpsme.GPSME_Main$ProgressTask.doInBackground(GPSME_Main.java:575)
:   at org.greenbot.technologies.gpsme.GPSME_Main$ProgressTask.doInBackground(GPSME_Main.java:1)
:   at android.os.AsyncTask$2.call(AsyncTask.java:287)
:   at java.util.concurrent.FutureTask.run(FutureTask.java:234)
:   ... 4 more
È stato utile?

Soluzione

You're getting the nullPointerException because you're expecting a JSON response, but since you have no network, there is no response to parse.

One way to prevent this code from running is to simply place a null check before you go into the loop:

if(json != null){
    for (int i = 0; i < json.length(); i++) {

            try {
                JSONObject c = json.getJSONObject(i);
                String parsed_results_formatted_address = c
                        .getString("formatted_address");
arrfortextviews.add(parsed_results_formatted_address);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
}

If it were me, I'd check for network connectivity before executing the code. This could be done before you call the execute of the AsyncTask :

ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //if there is a connection
    if (netInfo != null && netInfo.isConnectedOrConnecting()){
     ...put your code here...
}

Ultimately it just depends on whether you need the AsycTask to run if there is no connection.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top