0

I have a method that checks for an internet connection and depending on the state i want to provide different layouts

When there is an internet connection i want the layout to be

View rootView = inflater.inflate(R.layout.fragment_home, container, false);

when there is no connection i want it to be

View rootView = inflater.inflate(R.layout.fragment_null, container, false);

is it possible to do something like

View rootView = inflater.inflate(getstring(layoutchooser), container, false);

where layoutchooser is a defined String variable.

Alvin Moyo
  • 200
  • 1
  • 9
  • Use answer from http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out to detect internet connection. Just create getstring which responses corresponding string according to internet connection. – Dmitry Gorkovets Mar 07 '17 at 14:08

1 Answers1

3

You can do something like this

View rootView = inflater.inflate(layoutChooser(), container, false);

private int layoutChooser() {
        if (isNetworkAvailable()) {
            return R.layout.fragment_home;
        } else {
            return R.layout.fragment_NULL;
        }
    }

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Richard K Maleho
  • 436
  • 6
  • 16