Android exception.getMessage() kills App - android

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.

Related

Exception Handling in Android Studio

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.

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);
}
}

Keep Logcat from deleting entries

In Eclipse, I notice that Logcat only retains a few dozen entries and deletes the older ones as soon as a new one come in. Is there a way to prevent this? I need my app to run for a long time and not lose any entries because my app eventually hangs or crashes after a few days, and I want to see if something in Logcat has been recorded.
I am not sure if this is the most elegant solution to the problem, but you can always increase the LogCat message size in Eclipse.
Window -> Preferences -> Android -> LogCat -> Maximum number of LogCat messages to buffer
The default is 5000, I believe. You can set it to be very high if you are planning to run your application for a long time.
i think you need to increase this show image
Here's a better solution:
Set the Default Uncaught Exception Handler. Whenever the app crashes, this will be called with the exception. Simply write a log entry saying it crashed then dump the logcat to a file. Finally, make sure you re-throw the exception to make sure the app crashes and funky things don't happen. Note: This is per thread, keep that in mind.
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("TAG", "---My app crashed just now---", ex);
//TODO: Dump logcat to file
throw new RuntimeException(ex);
}
});
if you want to keep your app running for days.. its better you capture your logs from adb shell.
the common shell command would be :
logcat -c \\ to clear previous logs
logcat -v time>yourLogs.txt & \\ to capture fresh logs

How to see the crash reason in Eclipse debugger

Following this Android tutorial: http://developer.android.com/resources/tutorials/hello-world.html I added two lines which should cause null pointer exception:
Object o = null;
o.toString();
Now I set breakpoint on the second line and start debugger. When debugger breaks, I click "Step over" and application crashes. However, I don't see any useful information in the debugger. Debug window shows ActivityThread.performLaunchActivity, Source window shows "No source found". I don't see any information about exception, null pointer, etc. in any Eclipse debugger window, and don't see anything pointing to my line of code that causes crash. So, what am I missing?
Edit. Maybe Android UI framework has its own exception handling mechanizm, which prevents me to see exception immediately in my code? Something like this happens in another UI frameworks, like WinForms, Qt, wxWidgets.
After exception occurs you should check Logcat window for details: there you find the entire stack leading to the line of code where exception is. In some cases exception will occur in some other class (not yours) - then you should look for your package/class name in the stack to find otu whether you're "responsible" for it.
Corresponding output will not appear in Logcat immediately - let it run for some time (or until it crashes).
Also you can set "Java exception breakpoint" so the execution will break whenever there is an exception.
You can see the error in the LogCat. Window->Show View->other->Logcat
Try something like this...
try {
Object o = null;
o.toString();
}
catch (Exception e) {
e.printStackTrace();
}
...and use the DDMS perspective in eclipse.
Ideally you want to catch specific exceptions so the catch block would be...
catch (NullPointerException npe {
npe.printStackTrace();
}
...but doing a 'catch all' for Exception as in my first example and using the eclipse DDMS perspective to view logcat output will give you a good head start.
Finally, I found useful information in the "Breakpoints" debugger window. It shows NullPointerException and points exactly to offensive line.

Getting next alarm information when there is no such function

I have this code in my app
Alarm1 = Settings.System.getString(getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
Its working on htcs,motorolas,but not on galaxy s phones.The application crashes.
Would the following catch the error without crashing the application service?
String Alarm1=null;
try{
Alarm1 = Settings.System.getString(getContentResolver(),
Settings.System.NEXT_ALARM_FORMATTED);
}
catch (Exception e) {
Log.i("Exception", "Exception next alarm not found = " + e);
}
if (TextUtils.isEmpty(Alarm1)) {
//if i am i here either no alarm is set or couldn't read it from the phone
//do something else
}
Unless there is a different code for the galaxy s, and can i find it.How can i make it throw an exception on a phone that works, for testing purposes?Thanks.
I have the same problem on a widget i developed, it seems that on Galaxy S there is no entry on settings.db with ID NEXT_ALARM_FORMATTED, this makes the app crash. Sadly using try/catch it's not enough to solve the issue, widget still crashes.
I don't have a Galaxy S to debug the issue, if you find any workaround (other than inserting using sqlite3 the row con settings.db) let me know. Maybe you can try to simulate this behaviour by passing an invalid ID to the Settings function, i will try later today...
P.S. To temporary fix this on galaxy s you can (via adb shell)
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
UPDATE "system" SET value='' WHERE name='next_alarm_formatted';
Settings.System.NEXT_ALARM_FORMATTED is deprecated since API 21. Use the following instead:
AlarmManager.AlarmClockInfo alarmInfo = am.getNextAlarmClock();
where am is an instance of AlarmManager.

Categories

Resources