-2

I am creating an Android app and want to disappear retry button when there is network and it should be visible when there is no network, so the user can retry to load.

Aniket Jadhav
  • 166
  • 11

3 Answers3

1

In your .xml layout file within Button tag make button invisible as default

 android:visibility="invisible"

Create a common class to check connectivity

 public class ConnectionDetector {
    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }
}

Check the internet connction in your activity/ fragment

       ConnectionDetector cd;
        Boolean isInternetPresent = false;  

         cd = new ConnectionDetector(mContext);
            isInternetPresent = cd.isConnectingToInternet();
            if (isInternetPresent) {
              // Call your method or what ever 
            } else{
               button .setVisibility(View.VISIBLE);
}
Pavan Bilagi
  • 1,618
  • 1
  • 18
  • 23
0
if(isOnline(context))
    show
else 
    retry

check availability

public boolean isOnline(Context context) {

     ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo netInfo = cm.getActiveNetworkInfo();
     if (netInfo != null && netInfo.isConnectedOrConnecting()) {

         return true;
     } 
     else {
         return false;
     }

 }
Kishore Jethava
  • 6,666
  • 5
  • 35
  • 51
  • While this works, this is bad practice, because you have to actively check. Rather than doing this you should use a BroadCastReceiver and listen for connectivity changes. – A. Steenbergen Jan 03 '16 at 10:38
0

While the other answers do work, they rely on actively checking if the internet is available, which is fine if you don't want your ui to be responsive to connectivity changes, but bad practice if you want your ui to react to connectivity changes when they occur (aka losing internet connection).

It is better to get notified when connectivity changes by using a BroadCastReceiver.

In this way, your app only does work, when it is needed and is also able to change the ui state instantly should the network conditions change.

How to do it is described in this answer here

Community
  • 1
  • 1
A. Steenbergen
  • 3,360
  • 4
  • 34
  • 51