1

I fetch JSON data through an AsyncTask in my activity like so:

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    // Load the plants via AsyncTask
    new LoadItems().execute();
}

public class LoadItems extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONData();
        return null;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        updateList();
    }
}

But before fetching data, I need to check the connectivity. So I created the following class, thanks to snippets of codes from others:

public class ConnectionCheck {

public static boolean isConnectionOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e)          { e.printStackTrace(); }
      catch (InterruptedException e) { e.printStackTrace(); }

    return false;
}

// Dialog box for connection failure
public static void showConnectionFailureDialogBox(final Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(R.string.str_dialogBoxMessage);
    builder.setPositiveButton(R.string.str_dialogBoxButton,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.dismiss();
                    ((Activity) context).finish();
                }
            });

    AlertDialog alert = builder.create();
    alert.show();
}

}

And then I call those specially made functions like this:

@Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (!ConnectionCheck.isConnectionOnline()) {
         ConnectionCheck.showConnectionFailureDialogBox(MyActivity.this);
            this.cancel(true);
        }
    }

A dialog is supposed to show up when connection to the internet is non-existent. However, it pops up a dialog box every time. And when I checked the exit value I get, it's always 1. Never a 0. Is there something wrong with my code?

Also, it seems as if the code executes slowly? Is 'that' place the proper place to check the connection?

UPDATE This may be late but, the problem resides in the emulator I used. Nothing's really wrong with the code. I can't use the method suggested in the answer, as I do need a connection to the Internet. I'm restricting my app to not executing the statements if it doesn't have any network connection, 'cause it'll crash. I've read somewhere that following the method you guys were suggesting, the condition will return true even if there's no connection to the net; as long as the device is connected within a network. Or something along those lines.

  • are you trying to check connectivity of your api's server (the ip address) or connectivity of internet connection? – Lucas Crawford Aug 11 '15 at 23:57
  • I need to fetch data from the Internet so I am checking internet access. I've read here that this is one of the valid ways to check for actual connectivity (http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts). –  Aug 12 '15 at 00:03
  • @zerobasedindex has answered what I was going to say :P. That should be the accepted answer – Lucas Crawford Aug 12 '15 at 06:08

1 Answers1

1

I'd try using a more Android API centric way of checking for connectivity. We use the following method within a helper class to check. It won't always be triggered, but works well enough for our purposes.

public static boolean hasConnectivity(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected());
}

You'll need to add the following permission as well if you haven't already:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
zerobasedindex
  • 1,291
  • 9
  • 5