Reputation: 1216
I want to put a network check for all Activities, so that if no network is available, a Dialog box will appear and has to finish the current Activity.
For that I created a ConnectionDetector file to check the connection.
In this java file I created a Dialog box.
When I click the Dialog box Button, the calling Activity has to be finished.
How to send current activity as parameter?
My Activity
if (!ConnectionDetector.isConnectingToInternet()) {
ConnectionDetector.noConnectionDialog(getApplicationContext(), this);
}
ConnectionDetector.java
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public static boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) AppController.getContext().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;
}
public static void noConnectionDialog(final Context context, final Activity activity) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Network error");
dialog.setMessage("There seems to be a connection problem. Please check your network connection and try again");
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
dialog.show();
}
}
It is getting null pointer exception , activity is not getting finished.
Upvotes: 3
Views: 1546
Reputation: 7
public static void noConnectionDialog(final Context context, String c) {
Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.nointernet);
Window window = dialog.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
ImageButton close;
close = dialog.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
if (c.equals("1")) {
dialog.show();
} else {
dialog.dismiss();
}
}
Upvotes: 0
Reputation: 327
If you are always going to use show this dialog form activity you can also do
public static void noConnectionDialog(final Context context) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Network error");
dialog.setMessage("There seems to be a connection problem. Please check your network connection and try again");
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
((Activity)context).finish();
}
});
dialog.show();
}
Upvotes: 2