Coders' Guidebook

Why is my app crashing? Five ways to spot a bug using Android Studio and the Logcat

In this article, we will explore five ways of identifying (and resolving) bugs when developing an Android app.

1 - Find any red warnings

Android Studio is generally pretty good at finding bugs in your code. If Android Studio spots something that will crash your app then it will often highlight it in red. You must resolve all red warnings before your app will run. Simply press Project > app and scan the folders for files underlined in red. In the example below, it is the MainActivity.kt file which contains the bug.

spot-bugs-which-cause-android-app-to-crash.png

If you then open the file you will find the offending code highlighted in red. In this case, the phrase 'setContntView' is highlighted because of a typo.

error-in-code.png

In addition to finding the error, Android Studio will often offer potential resolutions. Simply select the red code then press the alt and enter keys on your keyboard. A drop-down menu will then appear with some possible fixes. Sometimes you need to rename the reference and fix a typo (like in this example), other times you may need to import a missing function or perform another task to get your code working.

rename-reference.png

2 - Google is your friend

Sometimes the suggested resolutions from Android Studio don't quite solve the problem. Maybe removing one error creates another, or perhaps the proposed solution just isn't relevant. In which case, it may be time to turn to the great wide web for help. If you hover over the error in Android Studio with your mouse then it should describe the issue. In the example below, recipeToShow is throwing a 'Type mismatch' error and Android Studio even shows what it was expecting (Int as a parameter instead of Recipe).

rename-reference.png

To resolve this error, we can simply change the function to take Int as a parameter instead of Recipe. While not all resolutions are that simple, chances are somebody else has encountered the same error before and fixed it. That's where Google comes in! Simply copy and paste the Android Studio error description into Google and see what the Android community can come up with. Some good places to check are Stack Overflow, the Android Developers website and your trusty Coders' Guidebook.

3 - What does the Logcat say?

Red errors are not the only way of spotting bugs in your code. Android Studio also contains a Logcat which displays system messages (including errors). You can access the Logcat by clicking the tab in the bottom left corner.

logcat.png

The Logcat is best used while your app is running on a virtual device. So, load up your app and expand the Logcat. You will likely see a continuous stream of messages. We can filter the messages to see which relate to errors by changing one of the Logcat dropdown menus from 'Verbose' to 'Error'.

logcat-error.png

You can now refer to the error messages that appear in the Logcat at the moment your app crashes. Maybe your app crashes the moment it loads, or perhaps the app crashes when you attempt a certain action. Either way, the Logcat will record the reason for the crash.

But how do you identify which error is causing the app to crash? Well, the best place to start is to find an error relating to a specific bit of your code. Scroll through the Logcat messages until you find a line containing one of your app's files is highlighted in blue. The error message will state the name of the file and line number causing the error. In the Logcat output below, we can see the code beginning on line 34 in the Recipes.kt file is causing the app to crash.

logcat-error-in-code.png

We can then refer to the Recipes.kt file and see if the error can be fixed. You could even search the internet for the error description given by the Logcat: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

4 - Use Logcat messages to check for bugs

How else might you be able to use the Logcat to find bugs? One way is to print messages to the Logcat at various checkpoints throughout the app. If the code runs successfully then a message will be printed in the Logcat, whereas if the code contains a bug then the message will not be printed and you then know which area of your app needs closer attention.

To print a message in the Logcat, first declare the following variable in the Kotlin file you are working on (if you are not sure where the variable should go then see the full code):

private val TAG = MainActivity::class.java.simpleName

This TAG variable will be printed at the beginning of the Logcat message. It contains the name of the file we are working on and so will help us locate the message in the Logcat output (note you may need to replace 'MainActivity' with the name of your chosen file).

The code which prints the Logcat message itself will look like the following:

Log.d(TAG, "onCreate called.")

You should look to introduce this code at the point in your file where you want the checkpoint to be. Log.d means the message will be printed to the Logcat under the 'debug' filter. The message itself is then written in brackets. It begins "MainActivity::class.java.simpleName" (because this is what is stored in the TAG variable) and ends "onCreate called.". You could change "onCreate called" to whatever message you think best describes the checkpoint.

Putting this all together, if you wanted to a message to be printed to the Logcat when the onCreate function is fired then your MainActivity.kt file would look like this:

//Note you may need to import the Log class
import android.util.Log
		
class MainActivity : AppCompatActivity() {

    private val TAG = MainActivity::class.java.simpleName

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d(TAG, "onCreate called.")
    }
}

When your app is run on a Virtual Device, you can then refer to the Logcat and see your message has been printed. It may help if you filter the messages by typing the name of the file into the search box.

logcat-comments.png

We are just scratching the surface of the Logcat here and will explore these topics in much greater depth in upcoming tutorials. For example, you could instruct the Logcat to print variables and other figures which may be useful for diagnostic purposes.

5 - Comment out problematic code

Comments are a great way of preventing code from being read when your app is being run without deleting the code itself. You can use comments to prevent single lines of code or entire methods from being run, and thereby see if they interfere with your app.

How you insert comments depends on the file type and how many lines you want to comment out. For Kotlin files, if you want to comment out a single line of code then simply put // at the beginning. On the other hand, if you wish to comment out multiple lines then put /* at the beginning of the first line and */ at the end of the last line.

class Recipes : AppCompatActivity() {
	
    private var mSerializer: JSONSerializer? = null
    private var recipeList: ArrayList? = null
	
    //This is how you comment out a single line of code
	
    //private var recyclerView: RecyclerView? = null
    private var adapter: RecipeAdapter? = null
    private var showDividers: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
		
        //This is how you comment out several lines of code
		
        /*btnNewRecipe.setOnClickListener { view ->
            val dialog = NewRecipe()
            dialog.show(supportFragmentManager, "")
        }*/

        mSerializer = JSONSerializer("Recipes.json",
            applicationContext)
	}
}

For XML files, the same method is used to comment out code regardless of how many lines there are. Simply add <!-- at the beginning of the code and --> at the end.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">
	
    <!--This is how you comment out XML code-->

    <!--<TextView
        android:id="@+id/viewName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="24sp"
        android:layout_alignParentTop="true"/>-->

    <TextView
        android:id="@+id/viewCourse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="20sp"
        android:layout_below="@+id/viewName"/>

</RelativeLayout>

Comments have many uses for debugging and app development. In addition to quarantining sections of code (i.e. preventing code from being read while not deleting it), you can also use comments to leave notes for yourself (and others). For example, you could leave a note describing what progress you have made on debugging the app so when you resume later you can pick up right where you left off.

These five steps have hopefully given you a starting place for identifying bugs with your app. We will cover the debugging process and other aspects of Android Studio such as the Logcat in much greater depth in upcoming tutorials.

<<< Previous