Step #4: Dealing with Crashes
Most likely, you will not need this step.
But, sometimes, when writing Android apps, you will make mistakes. Your code will compile, but then it will crash at runtime. A crash is signaled by a dialog indicating that there was a problem. The look of that dialog varies by Android version, but a typical one is:
When that occurs, you can find out more about the crash by opening the Logcat tool in Android Studio. By default, this is docked along the lower edge. Opening it gives you access to all sorts of messages logged by apps and the operating system.
There will be lots of messages.
Ideally, Android Studio would help you narrow down the messages. It offers a couple of things for that:
- There is a message “severity” drop down (third from left in the screenshot below), showing options like “Verbose” and “Error” — crashes are logged at “Error” severity
- The end drop-down will default to “Show only selected application”, which will then (theoretically) limit the output to only messages logged by your app, or by whatever app is shown in the second drop-down
When you crash, you will get a red Java stack trace showing what went wrong:
8937-8937/com.commonsware.todo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.commonsware.todo, PID: 8937
android.content.res.Resources$NotFoundException: Resource ID #0x7f060000 type #0x12 is not valid
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2139)
at android.content.res.Resources.getLayout(Resources.java:1143)
at android.view.MenuInflater.inflate(MenuInflater.java:111)
at com.commonsware.todo.MainActivity.onCreateOptionsMenu(MainActivity.kt:14)
at android.app.Activity.onCreatePanelMenu(Activity.java:3388)
at com.android.internal.policy.PhoneWindow.preparePanel(PhoneWindow.java:631)
at com.android.internal.policy.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:1024)
at com.android.internal.policy.PhoneWindow$1.run(PhoneWindow.java:264)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
In this case, this comes from a modified version of this sample app, hacked to introduce a crash. Typically, you look for the top-most line that refers to your code. In this case, that is:
at com.commonsware.todo.MainActivity.onCreateOptionsMenu(MainActivity.kt:14)
The location (MainActivity.kt:14
) will be a link that you can click to jump to that particular line of code. That, plus the error message, will hopefully help you diagnose exactly what went wrong.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.