Exception Handling in Android Studio - android

I have written some simple on button click code. When I run my application and click on the button, it gives the following Error:
Unfortunately, MyApplication has stopped.
Code under the button is following:
public void onClick(View v) {
if (v == mCapture) {
try {
CaptureFingerPrint();
RegisterFingerprint();
} catch (Throwable e) {
mTextViewResult.setText(e.toString());
}
}
}
I actually don't want to close my application accidentally and display error in label as i done in exception part of the above code which does not restrict my application to close.
Important to mention that i does not face this error in android studio. I face it when APK installed and run directly on mobile,
Please anyone guide how to restrict my application to close on button click and displaying error in label. The same i done in c# without any issue.

Without posting the stacktrace, the only reason I see that can make your app crash is mTextViewResult being null or e.toString() providing a null response. Was mTextViewResult properly identified inside the layout? If yes, try replacing e.toString() with "" + e.getMessage().
It would be best, though, if you found and checked the stack trace.

Related

Xamarin.Forms app works on iOS, throws error on Android ("Object reference not set to an instance of an object")

I'm new to Xamarin.Forms.
I got an app that works well on iOS. However, on Android, it crashes after some time, and throws the following error:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance
of an object.
Debug says it happens on this code:
private void OnElementToggled(object sender, EventArgs e)
{
this.Element.IsToggled = this.Control.Checked;
}
This toggle turns an option on or off inside our app. The toggle works fine on iOS. It also works on Android, but if I navigate around the app and switch the toggle on/off a few times, I get the error. I only get this error on Android, and only after I navigate around. Also, I get it at different times on simulator vs device (Galaxy S5 Neo). The simulator can run longer before I get the error.
I'm dumbfounded. How do I fix this?
I've searched and found What is a NullReferenceException, and how do I fix it?. That solution doesn't seem to apply in my case, because my code works fine on iOS and initially on Android.
Thank you very much for your time and help.
Try/Catch is a basic C# concept, any intro book will cover it
private void OnElementToggled(object sender, EventArgs e)
{
try {
this.Element.IsToggled = this.Control.Checked;
catch (Exception ex) {
// use logging (ie, appcenter.ms) to log this exception
}
}

displaying runtime errors in android/ios installed app

I've been trying to get errors to display in a text field within the app for ease of error reporting from users.
I've had some success using this code I found on stackoverflow. It's used at the top level of the app but it's not working on device:
//start code
this.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, errorHandler);
function globalErrorHandler(event:UncaughtErrorEvent):void
{
var message:String;
//check for runtime error
if (event.error is Error)
message = (event.error as Error).getStackTrace();
//handle other errors
else if (event.error is ErrorEvent)
message = (event.error as ErrorEvent).text;
else
message = event.error.toString();
//do something with message (eg display it in textfield)
myTextfield.text = message;
}
//end code
At first this wouldn't work on the device and I thought it was because upon the error, when developing on the pc, flashplayer would display the actionscript popup with the error. Which you would need to click "dismiss all" or close and then the globalErrorHandler was called after and then the error written to the textfield. I thought this is what was keeping it from showing up on the device. However, by adding event.preventDefault() I was able to suppress the actionscript popup when developing on the desktop and the error was written to the textfield successfully. This was not the case however on the andriod device. It still just hangs on the error. It's as if the default error event cannot be suppressed on android.
Thanks for your time. Any help appreciated!
EDIT 22/09/2017: I was able to see the error on device finally. It had to do with while on desktop publishing the error would be shown. However, on device the behavior was different and something was covering the textfield, by bring it to the front on error I was able to see it. However, I still see that some errors deeper in the class hierarchy are not being caught.
In our project we have it simpler (and it is working):
stage.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
private function onUncaughtError(e:UncaughtErrorEvent):void
{
// Console is basically a TextField for debug/diagnosis output.
if (e.error) Console.error(e.error.getStackTrace());
e.preventDefault();
}
The other thing you should probably check is whether your TextField actually displays any text at all for there might be text embedding issues, unrelated to the error handling routine.
UPD: Loading SWFs so it doesn't mix with the parent.
var request:URLRequest = new URLRequest(path);
var context:LoaderContext = new LoaderContext;
context.applicationDomain = ApplicationDomain.currentDomain;
var loader:Loader = new Loader;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(request, context);

How to enable stacktrace in android studio? Where is its window?

I develop an app which has problem in HTTP execute method. Someone suggested me to check stacktrace. But I don't know how!
So how can I enable it? where is exactly its window?
I put --full-stacktrace in File > Settings > compiler > command-line options . So I just see Threads and Frames in Debugger window.
(I know about log cat and I use it, I need to use stack trace)
You're looking for Logcat. The keybind to bring it up is Alt+6. You can also bring it up by clicking on it at the bottom of android studio:
Perhaps you are catching the exception but ignoring the result, you can log your stacktrace like this:
public void doSomething() {
try {
//do something that might throw an exception
} catch (Exception e) { //be as specific as possible when catching an exception
Log.e("ExceptionTag", e.getMessage(), e);
}
}

Creating a log trace of the application life cycle

I have created an application that extensively requires user inputs and interaction and even though I have made sure that I test and catch every possible case that might throw an error I want to be able to create a mechanism that traces the error in case my application crashes on the field.
I want to be able to record the entire flow right from a button click till whatever the user might be selecting or the navigation between the pages in a log file such that in case my application crashes I'm able to study the trace file later and know exactly where the error occurred.
I'm very new to this sort of programming and therefore any pointers on the above will be very helpful! Thank you in advance :]
PS: I'm not even sure whether what im referring to will be correctly called a "log trace" or not so any edit is welcome. :)
EDIT : I also want to be able to save the error report generated and send it to a particular id (similar to 'send an error report to xyz).
UPDATE :
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
File myFiles = new File("/sdcard/ScanApp");
if(!myFiles.exists())
{
myFiles.mkdirs();
}
File myFile = new File("sdcard/ScanApp/log.txt");
myFile.createNewFile();
myFile.delete();
myFile.createNewFile();
String cmd = "logcat -d -v time -f "+myFile.getAbsolutePath()+ " -s ActivityManager:V";
Runtime.getRuntime().exec(cmd);
Logs.this.finish();
}
catch (Exception e)
{
flag=1;
error=e.getMessage();
}
I used this in a previous application for recording any application activity and make a textfile and save it to the SD card, but the contents weren't exactly what I was looking for. Is the solution im looking for something along these lines?
Here, check for the link for reference.
In here you create a class say ExceptionHandler that implements java.lang.Thread.UncaughtExceptionHandler..
Inside this class you will do your life saving stuff like creating stacktrace and gettin ready to upload error report etc....
Now comes the important part i.e. How to catch that exception.
Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
Your Activity may look something like this…
public class ForceClose extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
setContentView(R.layout.main);
}
}
Hope this helps...
You need to look up on Exception Handling. That is when your application crashes or any other app level errors occur, the code in the exception block executes. So in that place, log that error in a text-file and which solves your "log trace" issue.
Refer the link for beautiful examples.

Android exception.getMessage() kills App

I have a question. Let's say I have the following code:
try{
//do something that could throw an exception
}
catch(Exception e){
System.out.println(e.getMessage();
}
Executing this in the emulator works fine, but when I tried to run it on my phone, the app craches (NullPointerException, apparently "e" is null).
How can that be?
Nope. If exception occurs than e must have something inside (and thats the purpose).
If you use System.out to print your logs, you should be able to see the error in LogCat under the System.out tag. Try checking that out and come back again.

Categories

Resources