1

I have a button that performs 2 actions. One is to check for internet/server connection, and the other is to get data from server if there is internet/server connection.

The problem I faced now is that my button will only perform the action to check internet/server connection but will not follow up the result of that connection to the next action.

However, when I press the button again, it will perform the second action.

Is there something wrong with my codes? I need some advise on this.

Checking Internet/Server connection

public Boolean isOnline() {
        try {
            p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
            int returnVal = p1.waitFor();
            boolean reachable = (returnVal == 0);
            if (reachable) {
                new uploadDB(new uploadDB.returnResult() {
                    @Override
                    public void onFinish(String result) {
                        if (result.equalsIgnoreCase("success")) {
                             isInternetConnected = true;
                        } else {
                            isInternetConnected = false;
                            showdialog("No Internet Connection", "Connection to server failed.");
                        }
                    }
                }).execute("ping");
            } else {
                isInternetConnected = false;
                showdialog("No Internet", "Internet connection is needed to perform certain actions.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

Button Click

 @Override
    public void onHistoryClick(final int position) {

        isOnline();

        if(isInternetConnected == true)
        {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.setMessage("Retrieving History Information...");
                    pd.setIndeterminate(true);
                    pd.setCancelable(false);
                    pd.show();
                }
            });
            new uploadDB(new uploadDB.returnResult() {
                @Override
                public void onFinish(String result) {
                    if(result != null)
                    {
                        Intent intent = new Intent(MainActivity.this, HistoryYearActivity.class);
                        intent.putExtra("barrelUUID", barrelList.get(position).getBeaconUUID());
                        intent.putExtra("barrelName", barrelList.get(position).getBarrelName());
                        intent.putExtra("result", result);
                        startActivity(intent);
                        pd.dismiss();
                    }
                }
            }).execute("historypageall",barrelList.get(position).getBeaconUUID());
        }
    }
Miyamura
  • 85
  • 8
  • You are not making use of your `isOnline` method. – Sagar Balyan Feb 18 '19 at 08:10
  • what is the default value for **isInternetConnected**? – Kartik Feb 18 '19 at 08:10
  • You have poorly written your code, though i feel `isInternetConnected` is false the first time you click the button. – Sagar Balyan Feb 18 '19 at 08:12
  • @SagarBalyan in my logcat, it only shows that isOnline() method is called, but not the other method that resides in onHistoryClick() – Miyamura Feb 18 '19 at 08:12
  • There are far simpler methods for determining internet connectivity than this (and which are also synchronous) – PPartisan Feb 18 '19 at 08:13
  • @Kartik is is false – Miyamura Feb 18 '19 at 08:13
  • @SagarBalyan yes it is false when i initialize it – Miyamura Feb 18 '19 at 08:14
  • Are these methods in different classes? Because your value doesn't seem to change. You can try to log your boolean value just after calling the isOnline method. – Kartik Feb 18 '19 at 08:15
  • @Kartik i have logged it and yes it does change – Miyamura Feb 18 '19 at 08:17
  • Have you tried https://stackoverflow.com/questions/54742823/how-to-perform-2-actions-in-a-method-on-a-single-button-click/54742932#54742932 – Googlian Feb 18 '19 at 08:17
  • 1
    Your code is actually not dependent on the `isOnline` method. Shouldn't be using it inside an `if` block? `if(isOnline())` – Sagar Balyan Feb 18 '19 at 08:30
  • 1
    If your function return type is Boolean then why do you use a Boolean variable in the if condition? Just return true and false at proper places and check what the function returns in the button click if condition. Your function usually returns false only. That should not be the case – Kartik Feb 18 '19 at 08:30
  • What's the purpose of having an `isOnline` method when you can also directly connect to your server and provide proper error messages? – Zun Feb 18 '19 at 08:38

4 Answers4

1

Do you really want to ping google.com and see internet connectivity? You can try the tutorial below which tells how to check for internet.

https://www.androidhive.info/2012/07/android-detect-internet-connection-status/

Still, if you want to go with your approach, then you need to create an AsyncTask which will ping google.com and respond true or false, then inside onPostExecute, based on true or false, you can do your actual action. In that way, with a single method call, both tasks will be performed.

Async Task tutorial - https://www.journaldev.com/9708/android-asynctask-example-tutorial

private class MyAsyncTask extends AsyncTask<String, String, Boolean> {
 @Override
    protected String doInBackground(String... params) {
    //put your code that checks internet connectivity here.
    //return true if internet is connected else return false/
    }

 @Override
    protected void onPostExecute(Boolean result) {
       //the result variable contains the value returned from doInBackground.

        if(result){
             //do what you want to do when the internet is there
             //I believe here you need to write history related task that you are trying to do.
        } else{
             //show Toast or Alert mentioning that no internet is available.
        }
    }
}

Hope this helps.

Alok Gupta
  • 1,353
  • 1
  • 13
  • 29
  • does this method actually checks for internet availability or does it just checks for wifi connection? because even if i can connect to wifi, it does not mean there is internet. – Miyamura Feb 18 '19 at 08:22
  • You are right, it just checks for connectivity, it does not ping or something like that. So what you need to do is, put your ping related code in AsyncTask's doInBackground method and then based on its response you need to write your code inside onPostExecute which will do your second task. Let me edit my answer to have this information. – Alok Gupta Feb 18 '19 at 08:23
  • i will try it out and get back to you – Miyamura Feb 18 '19 at 08:32
  • @Miyamura please accept this answer if it helped you. Thank you – Alok Gupta Feb 18 '19 at 08:45
1

Use this method to check internet connection

public static boolean checkInternet(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        // Log.v("INTERNET", "Available");
        return true;
    }
    return false;
}

Then you can process like

if(checkInternet(context)) {
 // Internet is available
}

Advanced:

If you want to use listeners and callback when the internet checking process done you just call the interface method.

interface InternetCheck {
    void isAvailable();
    void isNotAvailable();
}

public Boolean isOnline(InternetCheck internetCheck) {
    try {
        p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal == 0);
        if (reachable) {
            new uploadDB(new uploadDB.returnResult() {
                @Override
                public void onFinish(String result) {
                    if (result.equalsIgnoreCase("success")) {
                        isInternetConnected = true;
                        internetCheck.isAvailable();
                    } else {
                        isInternetConnected = false;
                        internetCheck.isNotAvailable();
                        showdialog("No Internet Connection", "Connection to server failed.");
                    }
                }
            }).execute("ping");
        } else {
            isInternetConnected = false;
            internetCheck.isNotAvailable();
            showdialog("No Internet", "Internet connection is needed to perform certain actions.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}


public void yourButtonClickEvent() {
    isOnline(new InternetCheck() {
        @Override
        public void isAvailable() {
          // Now Internet is available
        }

        @Override
        public void isNotAvailable() {

        }
    });
}
Googlian
  • 6,077
  • 3
  • 38
  • 44
  • does this method actually checks for internet availability or does it just checks for wifi connection? because even if i can connect to wifi, it does not mean there is internet. – Miyamura Feb 18 '19 at 08:18
  • You don't want to check using ping command just write a callback if your server is not reachable using `socket exceptions` in HTTPCLIENT https://github.com/smarek/httpclient-android – Googlian Feb 18 '19 at 08:21
  • Did you try my latest code https://stackoverflow.com/questions/54742823/how-to-perform-2-actions-in-a-method-on-a-single-button-click/54742932#54742932 – Googlian Feb 18 '19 at 08:28
  • i will try it out and get back to you – Miyamura Feb 18 '19 at 08:31
  • 1
    hi i have tried it and it works just like i wanted it too. thank you sir – Miyamura Feb 18 '19 at 08:39
0

Your isOnline() method will always return false. As you haven't returned any value in your try block.

Find below link to check your internet connectivity

Check connectivity (developer.android)

Or, check this below solution:

Check connectivity

After creating your check connection method, use that function in your onHistoryClick method on button click.

Muhammad Awais
  • 448
  • 5
  • 17
0

isOnline() sets isInternetConnected = true after an async operation. Essentially you are not waiting for that flag to be set/re-set and performing if(isInternetConnected == true). You should chain these two process, ie, perform the second task of get data from server if there is internet/server connection after you know from isOnline() that the async operation has completed.

Running these two dependent tasks independently will not help here.

Arka Prava Basu
  • 2,366
  • 3
  • 18
  • 34