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 try my ans that will definitely works – Pavan Bilagi Jan 03 '16 at 09:20
-
For actively responding to losing internet connection see this answer: http://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app – A. Steenbergen Jan 03 '16 at 10:44
3 Answers
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);
}

- 1,618
- 1
- 18
- 23
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;
}
}

- 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
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

- 1
- 1

- 3,360
- 4
- 34
- 51