---
image: https://i.imgur.com/tFW9IxW.png
---
# How to Solve Technical Issues - Android - OntraQ.org
If you are reading this guide, something has gone wrong within your app. Don't worry when this happens, this is a normal part of development. This guide is written to help you identify and fix your issues.
:::info
This guide explains the basic process professional engineers follow every day as they write new code and build systems. Debugging with approaches like the ones below is a daily occurrence in the field as a software engineer. **Debugging things that went wrong is a core skill as a software engineer, and a skill that must be rigorously developed over time.**
:::
**Jump to the relevant section of the guide:**
* [Something weird is happening with my emulator or Android Studio](#Something-weird-is-happening-with-my-emulator-or-Android-Studio)
* [My app is crashing with a dialog and then exits](#My-app-is-crashing-with-a-dialog-and-then-exits)
* [My app can't compile or build because of build errors](#My-app-can’t-compile-or-build-because-of-build-errors)
* [My app runs and doesn't crash but it doesn't do what I expect](#My-app-runs-and-doesn’t-crash-but-it-doesn’t-do-what-I-expect)
* [I tried to debug but I can't figure it out and I need help](#I-tried-to-debug-but-I-can’t-figure-it-out-and-I-need-help)
------
## Something weird is happening with my emulator or Android Studio
Be sure to [follow this checklist](https://hackmd.io/s/rkTSyWCa7) if things are acting strange or something isn't working and you can't figure out what is going on:
1. Uninstall the app on your emulator
2. Restart Android Studio and Emulator
3. Clean and Re-build Project
4. Re-sync with Gradle
5. Re-run the App
To see how to do these five steps, [follow this checklist on cleaning your project](https://hackmd.io/s/rkTSyWCa7).
**Still having issues?** If you still have problems such as an issue with the emulator, or a weird Android Studio error, be sure to check this [troubleshooting Android Studio guide](https://hackmd.io/s/r1KlxitOX).
---
## My app is crashing with a dialog and then exits
When building Android apps, your app is bound to crash from time to time with a runtime exception. You know you have experienced a runtime exception when you see this in your emulator or device:

Don't worry though! This is a common occurence and there's a specific set of steps you can take to fix app crashes.
### 1. Find the Crash Stack Trace
Go into Android Studio and open up the "Logcat". Expand this monitor so you can read the log messages easily:

1. Scroll to **the bottom of the error** looking for a line that says `Caused by` all the way at the bottom of the red stack trace block. The "original cause" towards the bottom of the block is the important part of the error, ignore most of the rest of the stack trace above that segment.
2. Locate that bottom-most `Caused by` line as well as the line that has the blue link with the name of your activity i.e `VideoActivity.java:13`. Copy these onto your clipboard and paste them both into a separate text file for easy review.
In this case the bottom-most "Caused by" line and the adjacent blue file link copied together looks something like:
```
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Intent.getStringExtra(java.lang.String)'
on a null object reference
at com.ontraq.flixster.VideoActivity.<init>(VideoActivity.java:13)
```
Note that the top part of the stack trace block above that line noting `FATAL EXCEPTION` and the first portion with the `java.lang.RuntimeException` are much more generic errors and are less useful than that final bottom-most "Caused by" exception captured above which points to the real culprit.
:::warning
**Not seeing a relevant red error message stack trace like this?** Make sure to run the app and re-trigger the crash. If that doesn't work, restart the emulator and/or Android Studio, re-run the app and then **re-trigger the crash**.
:::
### 2. Identify the Exception
Next, we need to identify the actual issue that this stack trace is warning us about. To do this, we need to identify the following elements of the exception:
1. File name - What file is this exception happening in?
2. Line number - Which line of code is triggering the exception?
3. Exception type - What is the type of the issue?
4. Exception message - What are the details about the exception?
Consider the exception we copied above:
<img src="https://i.imgur.com/xHOq5oE.gif" width="900" /><br/>
This exception needs to be translated to identifying the following elements for **your particular crash**:
| Element | Identified culprit |
| ------- | ---- |
| **Filename** | VideoActivity.java |
| **Line Number** | Line 13 |
| **Exception Type** | `java.lang.NullPointerException` |
| **Exception Message** | `Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference`
### 3. Understand why this error occurred
In this step, you want to go to the exact file and the line of code that is causing the exception based on the filename and number identified above (in this case `VideoActivity.java, line 13`. **This line of code in this file is the one that is causing the exception to occur.**
You can get to this line automatically by **clicking the blue link found in the error trace**. Once we navigate to the right line of code in Android Studio, we need to understand the type of exception and what this can tell us about what is going wrong. As you work on apps, you'll see many kinds of exceptions, but the most common types are the following:
* `NullPointerException` - This means that **some object is null when it shouldn't be**. In other words, we are calling a method on an object or passing an object that is null (has no value). This usually means **we forgot to set the value** or **the value is being set incorrectly**.
* `IndexOutOfBoundsException` - This means you are **trying to access an element of a list that doesn't exist** (i.e access item 3 in a list that is only 2 items long). Generally this is fixed by changing the code such that the invalid list item is no longer accessed.
There will be other error types but these two will come up most frequently.
### 4. Try to fix the root cause of this crash
Generally the next step from here is to fix the exception often through one or more of the following:
1. Adding an if statement to guard the code from running for a condition
2. Changing the order of the code running to fix code running too early
3. Changing some incorrect lines of code causing the invalid behavior
4. Setting up a variable with data that should exist but currently doesn't
For example, if the crash is a `NullPointerException` happening on a particular line of code, you'd want to ask yourself questions like:
* Which variable or item is null on this line?
* Why is this variable or item null and what value did I expect? Do I have a typo or issue causing it to be null accidentally?
* Do I need to add an if statement around the code block to make sure it doesn't run when this variable is null?
* Did I put this code block in the wrong place in the app, wherein data I expect to have doesn't exist here?
Then work from these questions until the issue is resolved or you [need to ask for help](#I-tried-to-debug-but-I-can’t-figure-it-out-and-I-need-help).
-----
## My app can't compile or build because of build errors
In this case, your app doesn't run because of build errors preventing the code from compiling.
### Reviewing the specific build errors
The best way to debug this is to:
1) Open the Build log window and see what Android Studio is complaining about. The Build log window can be opened by clicking on the 'Build' tab towards the bottom of the Android Studio screen.
<img src="https://i.imgur.com/IBosElw.png" width="500"/>
Once you have opened the 'Build' window, you can get a better sense of what the problem is.
<img src="https://i.imgur.com/E0xwrVS.png" width="1000"/>
In this specific example, we can look at the Build failed window and see that under 'Android Issues', the main error was 'error: attribute 'android:ID' not found. Above this line, we see that this error came from layout/activity_main.xml.
This means that in our activity_main.xml, we should search for where the file has the instance `android:ID` and fix it to be `android:id` ('id' should not be capitalized!).
### Common Build Errors
Common build errors can include:
* Typos or casing issues in an XML file: `android:ID` needs to be `android:id`
* If you have a syntax error in your XML file, open up your activity files and look for any red squiggles or issues. **If a single XML file can't be parsed, then the app can't build**
* Make sure that if you drag an image into the app, that the **image filename must contain only lowercase a-z, 0-9, or underscore**. If you have an image loaded with the name `My Awesome File.png`, then you'll need to right-click and rename that file to `my_awesome_file.png`.
:::info
**Have a weird build error?** You may also need to [clear the project caches](https://hackmd.io/s/ByTRUq-Y#clear-project-caches) and/or restart Android Studio in which then the build error will resolve itself.
:::
### Importing Classes
Android system classes are Java objects that are provided by the Android framework to use in your apps, this includes classes like: `TextView`, `ImageView`, `Button`, `Activity`, and hundreds of others. These built-in classes power your Android apps. However, in order to use any built-in class, **the file needs to import each class at the top**, which looks like:
```java
// Near the top of the file
import android.widget.ImageView;
import android.widget.TextView;
```
Often times when you're writing new code, Android Studio will start complaining about classes that need to be imported and the class (i.e `TextView`) might be **underlined in Red**. The shortcut to fix this is to click on the red class and then press: (Option + Enter) to import the class into the top of your file.
However, you can also configure your settings more so that the necessary classes will all be automatically imported when needed.
1. Go to Android Studio -> Preferences
<img src="https://i.imgur.com/yRXt10b.png" width="500"/>
2. In the Search Box , type in "Import" to easily go into the "Auto Import" section. Check the boxes for "Add unambiguous imports on the fly" and "Optimize imports on the fly". For "Insert imports on Paste", select "All"
<img src="https://i.imgur.com/8FRgKcL.png" width="500"/>
----
## My app runs and doesn't crash but it doesn't do what I expect
If you are in this section then your app compiles and builds on the emulator, and there isn't any crash BUT the app just doesn't work how you want.
The best way to debug this is to test assumptions you have about the code in key sections related to what isn't working. The easiest way to verify assumptions is to **simply log or toast variable values to make sure they are what you expect them to be**.
### Find the Relevant Code
First, navigate to the **section of code most closely linked to the issue you are having**.
For example, if you are expecting to see text displayed on the screen after sending a result from one activity to another, then go to the `onActivityResult` method in the activity that is displaying the text.
In this relevant area is where you want to begin testing your assumptions about the state and value of different variables.
### Toasting Messages
In order to test your assumptions or check the value of variables, you can print short messages as alerts that show up at the bottom of your app with a toast.
For example, if I expect to see text displayed coming back from another activity, I might have code like the following:
```java
// MainActivity.java
// I want to display a message sent from the other activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// REQUEST_CODE is defined earlier as a constant, it's a number
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
// Extract value from result extras sent back by the other activity
String myValue = data.getExtras().getString("myvalue");
}
}
```
I might want to make sure that the value is what I expect by printing this out with a toast inside of the if statement:
```java
// Toast the name to display temporarily on screen
Toast.makeText(getApplicationContext(), "Value is: " + myValue, Toast.LENGTH_SHORT).show();
```
And then this message will display at the bottom when the app runs and that line of code executes. I can then use this to investigate different variables to help me catch my issue.
### Logging Messages
While developing your app, sometimes it can be very useful to print more frequent messages to see if certain parts of the code are being executed, or what the value of a variable is at a particular point. In this case, you don't want a ton of toasts popping up in your app, and instead will want to **print log messages**.
Below is an example of how we can print a message in Logcat when a button is clicked, and then easily look for the message in Logcat:
1. Printing the log message when a button is clicked
```java
// myValue variable is defined earlier in the code
String myValue = ...some code here...;
// Setup our click listener
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// log a message
// the first string argument (in this case: "Caren") is how we can filter for our message in logcat
// the second string argument is what will be printed as the message
Log.i("Caren", "Button clicked with value: " + myValue + " !");
}
});
```
2. Look for the message in the Logcat by filtering for the tag you had given your log message. In this example, our tag was "Caren":
<img src="https://i.imgur.com/XXQbmUp.png" width="1000"/><br/>
We can then **put these log messages anywhere in our code** in a similar way to the toast messages, to verify any of our assumptions and investigate why our code isn't working as expected.
-----
## I tried to debug but I can't figure it out and I need help
If you have been trying to debug for an hour or two and you still can't figure this out, please message hello@ontraq.org or Instant Message your TAs on Slack or WhatsApp. Be sure to collect the following information first:
1. **Be able describe the specific problem** - What's the specific step and issue (don't say "doesn't work", be more specific). Mention specifically what you are trying to do ("delete the final flashcard") and then what happens unexpectedly ("the app crashes after I click the delete button").
2. **Show us the code** - Take screenshots of the relevant code snippets that are associated with the work you are doing in XCode or Android Studio, and make sure to include all the code around where the problem is likely to be occurring.
3. **Show us the error or crash message** - _If there's an app crash and the app exits_, share the screenshot of the full technical error message and stack trace in the logs (in XCode or inside Android Studio LogCat).
With this information provided and the screenshots taken as [described in this guide](https://hackmd.io/s/ryZxuyHTX), it will be much easier for anyone to help you work through the issue.