Open AlertDialog after a crash - android

I made an abstract fragment that other fragments extend with the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
paramThrowable.printStackTrace(printWriter);
String s = writer.toString();
Utils.logToFile(s);
emailReport(s); ///<<<<<
if (oldHandler != null) oldHandler.uncaughtException(paramThread, paramThrowable); //Delegates to Android's error handling
else System.exit(2); //Prevents the service/app from freezing
}
});
}
Just before handing the process back to the OS (after storing the exception in a file) I call emailReport(s);
private void emailReport(final String report) {
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.crash_report))
.setMessage(getString(R.string.send_crash_report))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, "Crash Report");
intent.putExtra(Intent.EXTRA_TEXT, report);
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
I want the alert dialog to show before the OS takes control so the user can either open his email client to send me the crash or cancel and close the app. The debug stops on the line that creates the alert dialog but after that, it jumps to the end of this method and from there, back to the old handler.
It could be another exception but I don't know that for sure and I can't catch it because I'm already in the middle of processing the current exception. Is there something wrong in the code? if not, how can I see what happens when trying to create the alert dialog?
UPDATE: I put the handling lines inside the setNegativeButton of the dialog, thinking it was shown but immediately closed but it didn't help:
if (oldHandler != null) oldHandler.uncaughtException(paramThread, paramThrowable); //Delegates to Android's error handling
else System.exit(2); //Prevents the service/app from freezing
}

I guess the problem is that you call imediatly the default handler which internally calls exit so your dialog is never been shown. So you method should look like this:
private void emailReport(final String report,
final Thread.UncaughtExceptionHandler oldHandler) {
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.crash_report))
.setMessage(getString(R.string.send_crash_report))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:support#example.com"));
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, "Crash Report");
intent.putExtra(Intent.EXTRA_TEXT, report);
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(oldHandler != null) {
//Delegates to Android's error handling
oldHandler.uncaughtException(paramThread, paramThrowable);
} else {
// Force to close the app now after handling the crash bug
System.exit(2);
}
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
And don't miss to remove the last two lines:
if (oldHandler != null) oldHandler.uncaughtException(paramThread, paramThrowable); //Delegates to Android's error handling
else System.exit(2); //Prevents the service/app from freezing

Related

Stop program execution until the option of dialogalert is chosen in android

If the location is disabled I want to show box and stop the execution process until I turn ON the location and come back to my app. Please Help with necessary suggestions.
function,
alertDialog.setTitle("GPS Setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(mContext, "Sorry we cannot proceed", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();// Showing Alert Message
You should use ProgressDialog at https://developer.android.com/reference/android/app/ProgressDialog.html
see this example:
private ProgressDialog progressDialog;
public void cerrarSession() {
try {
showDialog();
// do something
} catch (InternetException e) {
// some exception
e.printStackTrace();
}
}
private void showDialog() {
progressDialog = new ProgressDialog(SavingsRequestsManager.getActivity());
progressDialog.setCancelable(false);
closeDialog();
progressDialog.setMessage(SavingsRequestsManager.getActivity().getString(R.string.progress));
progressDialog.show();
}
public void closeDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}

How to execute the negative button function when dialog is canceled through back button?

I am having a dialog which must execute some code on canceled. I set a negative button but its not executing when dialog is canceled from back button.
here is my code.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Licence expired");
builder.setCancelable(false);
builder.setMessage("Your licence for " + url
+ " has been expired, Please renew it or select another server");
builder.setPositiveButton("Renew now",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Open url in webview
Intent intent = new Intent(MainActivity.this,
WebActivity.class);
intent.putExtra("ServerDomain", url);
startActivity(intent);
/*
* URL domain; try { domain = new URL(url);
* intent.putExtra("ServerDomain", domain.getHost());
* startActivity(intent); } catch (MalformedURLException
* e) { e.printStackTrace(); }
*/
/*
* String url = "http://www.google.com"; Intent i = new
* Intent(Intent.ACTION_VIEW);
* i.setData(Uri.parse(url)); startActivity(i);
*/
}
});
builder.setNegativeButton("Switch Server",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showServerList();
}
});
builder.create().show();
Create a cancel listner for dialog.
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
showServerList();
}
});

making phone call from DialogBox in Android

I have one DialogBox with 2 buttons. If we click the +ve button, it attempts to open the Dialing Pad; else if we click the -ve button it closes the dialog. When I click the +ve button it shows the null exception. If the same code executes without the DialogBox, it is fine.
Here is my code:
callDialog.setPositiveButton("Call Now", new android.DialogInterface.
OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
}
I've given permissions in the manifest file as <uses-permission android:name="android.permission.CALL_PHONE"/>
Try this..
Intent call = new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:phonenumber");
startActivity(call);
Remove the #Overrride line.
Like this:
callDialog.setPositiveButton("Call Now", new android.DialogInterface.
OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
}
----UPDATE-----
Since you havent posted any logcat, its hard to know where it crashes. Try this block:
AlertDialog.Builder callDialog = new AlertDialog.Builder(this);
callDialog.setTitle("My title");
callDialog.setMessage("My message");
callDialog.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
});
callDialog.setNegativeButton("Cancel", null);
callDialog.show();
Try the following---
Intent dial = new Intent(Intent.ACTION_DIAL);
//dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
startActivity(dial);
Use
Intent callIntent = new Intent(Intent.ACTION_CALL);
instead of this
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setAction("android.intent.action.DIAL"); // but this line is an optional one
callIntent.setData(Uri.parse("tel:044 6000 6000"));
startActivity(callIntent);
use this code......
String number = "tel:" + phonenumber;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(number));
startActivity(intent);
give permission in manifest: <uses-permission android:name="android.permission.CALL_PHONE" />
updated.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.menu_icon_pager).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage(
"Texting from dialog")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
String number = "tel:"+phonenumber ;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(number));
startActivity(intent);
}
})
.show();
}
});
}
Actually I called the AlertDialog from another Activity,so I need the context of called
Activity's Context reference.So I passed the Context as a parameter to Called Activity
Here is Called Activity's code
if(position == 1)new CalledByActivity().dailingDialogBox(param1,
param2,context);//Here I'm passing the context as param
Here CalledBy activity's implemented function
public void dailingDialogBox(final String param1,String param2,final Context context){
Here I implemented in +ve button click
Intent dail = new Intent(Intent.ACTION_DIAL);
dail.setData(Uri.parse("tel:"+station_Number));
context.startActivity(dail);//Here the "context" is reference of called Activity's context

Android - Show alert dialog in AsyncTask

I'm trying to show an alert dialog when a user fails to enter valid email and password to log in. Since the login process has to deal with HTTP request and JSON, I put it all in an AsyncTask and I'm not sure if that's the problem why my alert dialog can't show (I hope not). So this is method checkUser, which is called within onPostExecute of the AsyncTask class:
public void checkUser(JSONObject json){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
if (tag == login_tag){
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
// code omitted
} else{
// Error in login
mProgressDialog.dismiss();
builder.setMessage("Incorrect username/password")
.setTitle("Error")
.setNeutralButton("OK", new OnClickListener() {
public void onClick(final DialogInterface dialog,final int which) {
dialog.cancel();
}
}).create().show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Somehow my alert dialog can never show and I don't know why. If you have any idea what the reason of this problem is, please help me out. Thanks a lot!
EDIT: Turns out I only close my Progress Dialog after executing this method, so I decided to dismiss it before showing the alert dialog. But it still hasn't solved the problem.
So I solved this myself this way: somehow the Alert dialog only works outside the method checkUser. So I move the bits within the error if clause outside, below the dismiss() of Progress dialog in onPostExecute():
protected void onPostExecute(JSONObject json) {
checkUser(json);
mProgressDialog.dismiss();
try {
if (json.get(ERROR_MSG) != null){
String errorMsg = json.getString(ERROR_MSG);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(errorMsg)
.setTitle("Error")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create().show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And voila, it works!
P.s: I still don't know why the dialog can't show when put within checkUser though.
missing builder.create()
// Error in login
builder.setMessage("Incorrect username/password")
.setTitle("Error")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
}
}).create().show();

Android: How to show a dialog after user clicks "Okay" on a previous dialog

How come the AlertDialog that has the title "Location was saved to file" doesn't show up? It is the one that should be displayed after the user presses Okay on the first dialog.
I think it has something to do with threads, but I'm not sure.
SimpleDateFormat timeStampFormat = new SimpleDateFormat("MMMMM-dd-yyyy");
final EditText input = new EditText(EncounterActivity.this);
input.setWidth(75);
input.setText("Bear-Encounter-GPS-" + timeStampFormat.format(new Date()) + ".txt");
new AlertDialog.Builder(EncounterActivity.this)
.setTitle("Save GPS Location")
.setMessage("Please enter a filename")
.setView(input)
.setIcon(R.drawable.gps)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File fn = new File(root, input.getText().toString());
FileWriter gpxwriter = new FileWriter(fn);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write(ll.toUTMRef().toString());
out.close();
AlertDialog.Builder builder = new AlertDialog.Builder(EncounterActivity.this);
builder.setIcon(R.drawable.gps);
builder.setTitle("Location was saved to file");
builder.setMessage("Your GPS coordinates were saved to " + fn.getAbsolutePath())
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (IOException e) {
//ProfitBandit.alert(Shipment.this, "Couldn't write the file.");
Log.v("IOException", "Could not write file " + e.getMessage());
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
You CAN display an alert dialog from an alert dialog if you use the pattern showDialog(int) getInstanceSomeDialog and onCreateDialog(int) for both dialogs. So in my aboutAlertDialog I have:
builder.setPositiveButton("View EULA", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { //cancels itself?
showDialog(DIALOG_EULA_SHOW);
}
});
which in turn displays an EULA in yet another AlertDialog. OR you could just toss up a Toast as in:
Toast.makeText(Main.this,"Location Saved.", Toast.LENGTH_SHORT).show();
where Main is the activity class.

Categories

Resources