Adding An Alert Dialog Box With A Retry Button
I am working on a project where an alert dialog box appears if there is no internet connection on the phone. This alert dialog box says that Network is Unavailable and has a button
Solution 1:
This is just one example, you should implement AlertDialog as global variable for not creating one every time you try to make the request.
public void runTask () {
if(isNetworkAvailable())
{
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("ERROR !!");
builder.setMessage("Sorry there was an error getting data from the Internet.\nNetwork Unavailable!");
;
AlertDialog dialog = builder.create();
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
runTask();
}
});
dialog.show();
Toast.makeText(this, "Network Unavailable!", Toast.LENGTH_LONG).show();
}
}
Solution 2:
There is a small error in TeRRo's Code.
You are calling AlertDialog dialog = builder.create();
before adding Buttons so buttons are not adding up.
So I updated the code. This code will check for internet connection if internet is available, it executes whatever you want, if not, It displays Alert Dialog with two buttons.
Updated code:
if(isNetworkAvailable()) {
/* DO WHATEVER YOU WANT IF INTERNET IS AVAILABLE */
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("No Internet");
builder.setMessage("Internet is required. Please Retry.");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
InitiateDownload();
}
});
AlertDialog dialog = builder.create(); // calling builder.create after adding buttons
dialog.show();
Toast.makeText(this, "Network Unavailable!", Toast.LENGTH_LONG).show();
}
isNetworkAvailable() is a Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Note: builder.setCancelable(false);
- so user won't able to dismiss dialog by pressing back button. Happy coding.
Post a Comment for "Adding An Alert Dialog Box With A Retry Button"