I want to check for internet connection and if it's available call getData()
but if it's not available show a dialog with RETRY and CANCEL options.
If RETRY is clicked check for internet connection; if available call getData
but if it isn't available, show the dialog again (something like looping).
Alternatively, if CANCEL is clicked exit the app altogether.
I'm using this class to check for network availability and internet connection:
public class NetworkCheck {
public static boolean isAvailableAndConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
boolean isNetWorkConnected = isNetworkAvailable && cm.getActiveNetworkInfo().isConnected();
return isNetWorkConnected;
}
}
And in MainActivity I do this:
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data
getData();
} else {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("No Internet Connection");
alertDialogBuilder.setMessage("Failed to load. Please ensure ypu're connected to the internet and try again");
alertDialogBuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
From the above codes, I have three questions:
- In line
if (!NetworkCheck.isAvailableAndConnected(context)) {
context is being highlighted in red and when I hover it, I see Cannot resolve symbol 'context'. If I leave the method empty or typethis
orgetActivity
; Android Studio complains. Which parameter show I pass the method? - Calling
finish()
will only kill the activity. Shoudn't the whole app be killed and how? - What else am I doing wrong?