Debug your app

Android Studio provides a debugger that allows you to do the following and more than:

  • Select a device to debug your app on.
  • Set breakpoints in your Java, Kotlin, and C/C++ code.
  • Examine variables and evaluate expressions at runtime.

This page includes instructions for bones debugger operations. For more documentation, besides see the IntelliJ IDEA debugging docs.

Enable debugging

Before you lot can begin debugging, you need to prepare equally follows:

  • Enable debugging on your device:

    If you're using the emulator, this is enabled by default. But for a connected device, you need to enable debugging in the device programmer options.

  • Run a debuggable build variant:

    You must utilise a build variant that includes debuggable true in the build configuration. Usually, you can only select the default "debug" variant that's included in every Android Studio project (even though information technology'southward non visible in the build.gradle file). But if yous define new build types that should exist debuggable, y'all must add together `debuggable true` to the build type:

    Groovy

    android {     buildTypes {         customDebugType {             debuggable true             ...         }     } }                          

    Kotlin

    android {     buildTypes {         create("customDebugType") {             debuggable = true             ...         }     } }                          

    This holding also applies to modules with C/C++ code. (The jniDebuggable holding is no longer used.)

    If your app depends on a library module that y'all also want to debug, that library must also exist packaged with debuggable true so information technology retains its debug symbols. To ensure that the debuggable variants of your app projection receive the debuggable variant of a library module, be sure that you publish non-default versions of your library.

Start debugging

Y'all tin can start a debugging session as follows:

  1. Prepare some breakpoints in the app code.
  2. In the toolbar, select a device to debug your app on from the target device drop-downward menu.

    Target device drop-down menu.

    If you don't have any devices configured, then you demand to either connect a device via USB or create an AVD to employ the Android Emulator.

  3. In the toolbar, click Debug .

    If you see a dialog asking if you want to "switch from Run to Debug," that means your app is already running on the device and it will restart in lodge to begin debugging. If yous'd rather proceed the aforementioned example of the app running, click Abolish Debug and instead adhere the debugger to a running app.

    Otherwise, Android Studio builds an APK, signs it with a debug key, installs information technology on your selected device, and runs information technology. If you add C and C++ lawmaking to your project, Android Studio also runs the LLDB debugger in the Debug window to debug your native code.

  4. If the Debug window is not open, select View > Tool Windows > Debug (or click Debug in the tool window bar), and then click the Debugger tab, every bit shown in figure one.

    Figure 1. The Debugger window, showing the current thread and the object tree for a variable

Attach the debugger to a running app

If your app is already running on your device, you lot tin first debugging without restarting your app equally follows:

  1. Click Attach debugger to Android procedure .
  2. In the Cull Process dialog, select the process yous want to adhere the debugger to.

    If you're using an emulator or a rooted device, you can check Show all processes to see all processes.

    From the Use Android Debugger Settings from drop-down carte du jour, you can select an existing run/debug configuration. (For C and C++ code, this lets you reuse the LLDB startup commands, LLDB post-adhere commands, and symbol directories in an existing configuration.) If you don't have an existing run/debug configuration, select Create New. This selection enables the Debug Type driblet-downwards menu, where y'all tin select a different debug type. By default, Android Studio uses the Automobile debug type to select the best debugger pick for you, based on whether your project includes Java or C/C++ code.

  3. Click OK.

    The Debug window appears.

Notation: The Android Studio debugger and garbage collector are loosely integrated. The Android virtual automobile guarantees that whatsoever object the debugger is aware of is non garbage collected until after the debugger disconnects. This can event in a buildup of objects over time while the debugger is connected. For example, if the debugger sees a running thread, the associated Thread object is not garbage collected until the debugger disconnects, fifty-fifty if the thread has terminated.

Change the debugger type

Because unlike debugger tools are required to debug Java/Kotlin code and C/C++ lawmaking, the Android Studio debugger allows you to select which debugger type to utilize. By default, Android Studio decides which debugger to use based on which languages it detects in your project (with the Auto debugger type). Yet, you tin manually select the debugger in the debug configuration (click Run > Edit Configurations) or in the dialog that appears when you lot click Run > Attach debugger to Android process.

The debug types bachelor include the following:

Auto
Select this debug blazon if you lot want Android Studio to automatically choose the all-time choice for the code you lot are debugging. For example, if y'all accept any C or C++ lawmaking in your project, Android Studio automatically uses the Dual debug type. Otherwise, Android Studio uses the Java debug type.
Java
Select this debug type if you desire to debug only code written in Java or Kotlin—the Coffee debugger ignores whatever breakpoints or watches you set in your native code.
Native (available only with C/C++ lawmaking)
Select this debug blazon if you desire to use just LLDB to debug your code. When using this debug type, the Coffee debugger session view is not bachelor. By default, LLDB inspects but your native code and ignores breakpoints in your Java lawmaking. If you want to also debug your Java lawmaking, yous should switch to either the Auto or Dual debug type.

Native debugging simply works on devices that meet the following requirements:

  • The device supports run-as.

    To check whether the device supports run-equally, run the following command on the ADB shell that is connected to your device:

    run-as                            your-package-name                            pwd                          

    Replace your-package-name with your app's package name. If the device supports run-as, the control should return without any errors.

  • The device has ptrace enabled.

    To check whether ptrace is enabled, run the post-obit command on the ADB beat out that is continued to your device:

    sysctl kernel.yama.ptrace_scope                          

    If ptrace is enabled, the command will print the value 0 or an an unknown key error. If ptrace is not enabled, it volition print a value other than 0.

Dual (available but with C/C++ code)
Select this debug type if you want to switch between debugging both Java and native code. Android Studio attaches both the Java debugger and LLDB to your app process, 1 for the Java debugger and one for LLDB, and then you lot can audit breakpoints in both your Java and native lawmaking without restarting your app or changing your debug configuration.

In figure 2, observe the two tabs to the right of the Debug window title. Considering the app has both Java and C++ code, 1 tab is for debugging the native lawmaking, and the other for debugging Java code, as indicated past -coffee.

Effigy 2. Tab for debugging native lawmaking and tab for debugging Coffee lawmaking

Notation: If you are debugging native code that is optimized by the compiler, yous may get the following warning bulletin: This role was compiled with optimizations enabled. Some debugger features may non exist available. When using optimization flags, such every bit -O flags, the compiler makes changes to your compiled code to brand it run more efficiently. This tin can cause the debugger to report unexpected or incorrect information because information technology'due south difficult for the debugger to map the optimized compiled code back to the original source code. For this reason, y'all should disable compiler optimizations while debugging your native lawmaking.

Use the organisation log

The system log shows system messages while you debug your app. These letters include data from apps running on the device. If you want to use the system log to debug your app, make sure your code writes log messages and prints the stack trace for exceptions while your app is in the development phase.

Write log messages in your code

To write log messages in your lawmaking, utilise the Log class. Log messages help you empathise the execution menstruum by collecting the system debug output while y'all collaborate with your app. Log messages tin can tell you what part of your application failed. For more data about logging, encounter Write and view logs.

The following example shows how you might add log messages to decide if previous country information is available when your activeness starts:

Kotlin

import android.util.Log ... individual val TAG: Cord = MyActivity::class.java.simpleName ... class MyActivity : Activity() {     ...     override fun onCreate(savedInstanceState: Parcel?) {         ...         if (savedInstanceState != zip) {             Log.d(TAG, "onCreate() Restoring previous state")             /* restore state */         } else {             Log.d(TAG, "onCreate() No saved country bachelor")             /* initialize app */         }     } }                        

Java

import android.util.Log; ... public class MyActivity extends Activity {     individual static final String TAG = MyActivity.class.getSimpleName();     ...     @Override     public void onCreate(Bundle savedInstanceState) {        ...        if (savedInstanceState != naught) {             Log.d(TAG, "onCreate() Restoring previous state");             /* restore land */         } else {             Log.d(TAG, "onCreate() No saved country bachelor");             /* initialize app */         }     } }                        

During evolution, your code tin also catch exceptions and write the stack trace to the system log:

Kotlin

fun someOtherMethod() {     try {         ...     } catch (e : SomeException) {         Log.d(TAG, "someOtherMethod()", e)     } }                        

Coffee

void someOtherMethod() {     try {         ...     } catch (SomeException e) {         Log.d(TAG, "someOtherMethod()", e);     } }                        

Annotation: Remove debug log messages and stack trace print calls from your lawmaking when you are set to publish your app. You could do this past setting a DEBUG flag and placing debug log messages inside conditional statements.

View the system log

You tin view and filter debug and other system messages in the Logcat window. For case, you lot tin come across letters when garbage collection occurs, or messages that you add to your app with the Log class.

To use logcat, start debugging and select the Logcat tab in the bottom toolbar every bit shown in figure iii.

Figure 3. Logcat window with filter settings

For a description of logcat and its filtering options, see Write and view logs with Logcat.

Work with breakpoints

Android Studio supports several types of breakpoints that trigger different debugging actions. The most common blazon is a line breakpoint that pauses the execution of your app at a specified line of code. While paused, y'all tin examine variables, evaluate expressions, so go along execution line past line to determine the causes of runtime errors.

To add a line breakpoint, go on as follows:

  1. Locate the line of code where y'all want to pause execution, then either click the left gutter along that line of code or place the caret on the line and press Control+F8 (on Mac, Command+F8).
  2. If your app is already running, y'all don't need to update it to add the breakpoint—but click Attach debugger to Android proccess . Otherwise, start debugging by clicking Debug .

Effigy 3. A cerise dot appears next to the line when y'all prepare a breakpoint

When your lawmaking execution reaches the breakpoint, Android Studio pauses execution of your app. You can then apply the tools in the Debugger tab to place the country of the app:

  • To examine the object tree for a variable, expand it in the Variables view. If the Variables view is not visible, click Restore Variables View .

  • To evaluate an expression at the current execution point, click Evaluate Expression .

  • To advance to the next line in the code (without inbound a method), click Pace Over .

  • To advance to the first line within a method telephone call, click Pace Into .

  • To advance to the side by side line outside the current method, click Step Out .

  • To continue running the app normally, click Resume Program .

If your project uses any native code, by default the Auto debug type attaches both the Coffee debugger and LLDB to your app every bit two split processes, then you tin can switch between inspecting Java and C/C++ breakpoints without restarting your app or changing settings.

Note: For Android Studio to detect breakpoints in your C or C++ code, you need to utilize a debug blazon that supports LLDB, such every bit Auto, Native, or Dual. Y'all can change the debug blazon Android Studio uses by editing your debug configuration. To acquire more virtually the different debug types, read the section well-nigh using other debug types.

When Android Studio deploys your app to your target device, the Debug window opens with a tab or debug session view for each debugger procedure, as shown in effigy four.

Figure 4. Debugging native code using LLDB

  1. Android Studio switches to the <your-module> tab when LLDB debugger encounters a breakpoint in your C/C++ code. The Frames, Variables, and Watches panes are also available and work exactly equally they would if you lot were debugging Java code. Although the Threads pane is not available in the LLDB session view, you tin access your app processes using the driblet-down list in the Frames pane. Yous can learn more about these panes in the sections nearly how to debug window frames and inspect variables.

    Note: While inspecting a breakpoint in your native lawmaking, the Android organization suspends the virtual motorcar that runs your app's Java bytecode. This ways that you are unable to interact with the Coffee debugger or recall whatever state data from your Coffee debugger session while inspecting a breakpoint in your native code.

  2. Android Studio switches to the <your-module>-coffee tab when the Java debugger encounters a breakpoint in your Java code.
  3. While debugging with LLDB, y'all can utilize the LLDB terminal in the LLDB session view to pass command line options to LLDB. If yous accept certain commands that you would like LLDB to execute each fourth dimension you start debugging your app, either just before or just afterwards the debugger attaches to your app process, you can add together those commands to your debug configuration.

While debugging C/C++ code, you tin can also set special types of breakpoints, chosen watchpoints, that can append your app process when your app interacts with a particular cake of retention. To acquire more, read the section nigh how to add watchpoints.

View and configure breakpoints

To view all the breakpoints and configure breakpoint settings, click View Breakpoints on the left side of the Debug window. The Breakpoints window appears, as shown in figure v.

Figure 5. The Breakpoints window lists all the current breakpoints and includes behavior settings for each

The Breakpoints window lets you enable or disable each breakpoint from the list on the left. If a breakpoint is disabled, Android Studio does non pause your app when it hits that breakpoint. Select a breakpoint from the listing to configure its settings. You tin configure a breakpoint to be disabled at first and take the system enable information technology afterward a dissimilar breakpoint is hit. Y'all tin can likewise configure whether a breakpoint should be disabled afterwards it is hit. To fix a breakpoint for any exception, select Exception Breakpoints in the list of breakpoints.

Debug window frames

In the Debugger window, the Frames pane lets y'all audit the stack frame that caused the electric current breakpoint to be hit. This enables you to navigate and examine the stack frame and also inspect the listing of threads in your Android app. To select a thread, employ the thread selector drop-down and view its stack frame. Clicking the elements in the frame opens the source in the editor. You lot tin also customize the thread presentation and export the stack frame equally discussed in the Window Frames guide.

Audit variables

In the Debugger window, the Variables pane lets you inspect variables when the organization stops your app on a breakpoint and you select a frame from the Frames pane. The Variables pane also lets you evaluate advert-hoc expressions using static methods and/or variables available within the selected frame.

The Watches pane provides similar functionality except that expressions added to the Watches pane persist betwixt debugging sessions. Y'all should add watches for variables and fields that yous access frequently or that provide country that is helpful for the current debugging session. The Variables and Watches panes announced as shown in figure five.

To add a variable or expression to the Watches list, follow these steps:

  1. Brainstorm debugging.
  2. In the Watches pane, click Add .
  3. In the text box that appears, blazon the proper noun of the variable or expression yous want to watch and then press Enter.

To remove an item from the Watches list, select the item and and so click Remove .

You tin can reorder the elements in the Watches list by selecting an item then clicking Up or Down .

Figure 6. The Variables and Watches panes in the Debugger window

Add together watchpoints

While debugging C/C++ lawmaking, you can ready special types of breakpoints, called watchpoints, that can suspend your app process when your app interacts with a particular block of memory. For example, if you set two pointers to a cake of retentiveness and assign a watchpoint to it, using either pointer to access that block of retention triggers the watchpoint.

In Android Studio, yous can create a watchpoint during runtime by selecting a specific variable, but LLDB assigns the watchpoint to merely the block of memory the system allocates to that variable, not the variable itself. This is different from adding a variable to the Watches pane, which enables yous to observe the value of a variable but doesn't allow you to suspend your app process when the system reads or changes its value in retentivity.

Note: When your app procedure exits a office and the system deallocates its local variables from memory, yous need to reassign any watchpoints y'all created for those variables.

To set a watchpoint, you lot must run into the following requirements:

  • Your target physical device or emulator uses an x86 or x86_64 CPU. If your device uses an ARM CPU, and then yous must align the boundary of your variable'south accost in memory to either 4 bytes for 32-bit processors, or 8 bytes for 64-bit processors. Y'all tin can align a variable in your native code by specifying __attribute__((aligned(num_bytes))) in the variable deceleration, every bit shown below:
    // For a 64-bit ARM processor int my_counter __attribute__((aligned(8)));                        
  • You have assigned three or fewer watchpoints already. Android Studio only supports upwardly to 4 watchpoints on x86 or x86_64 target devices. Other devices may support fewer watchpoints.

Annotation: When debugging your app with 32-scrap ARM ABIs, adding a watchpoint or hovering over variables inside the code to investigate their values may cause a crash. As a workaround, please debug using 64-bit ARM, x86, or x86_64 binaries. This issue will be fixed in an upcoming Android Studio release.

If y'all run into the requirements above, you tin can add a watchpoint every bit follows:

  1. While your app is suspended on a breakpoint, navigate to the Variables pane in your LLDB session view.
  2. Right-click on a variable that occupies the block of memory yous want to track and select Add Watchpoint. A dialog to configure your watchpoint appears, as shown in figure vii.

    Effigy 7. Adding a watchpoint to a variable in memory

  3. Configure your watchpoint with the post-obit options:
    • Enabled: You can deselect this option if you want to tell Android Studio to ignore the watchpoint for the time being. Android Studio still saves your watchpoint and then yous tin can access it later in your debug session.
    • Suspend: By default, the Android system suspends your app procedure when it accesses a block of memory you assign to a watchpoint. You tin can deselect this choice if you don't want this behavior—this reveals additional options you can use to customize behavior when the system interacts with your watchpoint: Log bulletin to console and Remove [the watchpoint] when striking.
    • Access Type: Select whether your app should trigger your watchpoint when it tries to Read or Write to the block of memory the arrangement allocates to the variable. To trigger your watchpoint on either a read or write, select Any.
  4. Click Done.

To view all your watchpoints and configure watchpoint settings, click View Breakpoints on the left side of the Debug window. The Breakpoints dialog appears, as shown in figure 8.

Figure 8. The Breakpoints dialogue lists your current watchpoints and includes beliefs settings for each

After you add your watchpoint, click Resume Program on the left side of the Debug window to resume your app process. By default, if your app tries to access a cake of memory that you take prepare a watchpoint to, the Android system suspends your app process and a watchpoint icon appears next to the line of code that your app executed final, equally shown in figure 9.

Figure 9. Android Studio indicates the line of code that your app executes merely earlier triggering a watchpoint

View and change resource value display format

In debug mode, you can view resources values and select a dissimilar display format for variables in your Java code. With the Variables tab displayed and a frame selected, do the following:

  1. In the Variables listing, right-click anywhere on a resource line to display the drop-down list.
  2. In the drop-down list, select View as and select the format you want to use.

    The available formats depend on the data type of the resource you lot selected. You might see whatsoever one or more of the following options:

    • Class: Display the grade definition.
    • toString: Display string format.
    • Object: Brandish the object (an instance of a class) definition.
    • Array: Display in an assortment format.
    • Timestamp: Display date and time every bit follows: yyyy-mm-dd hh:mm:ss.
    • Auto: Android Studio chooses the best format based on the information type.
    • Binary: Brandish a binary value using zeroes and ones.
    • MeasureSpec: The value passed from the parent to the selected kid. See MeasureSpec.
    • Hex: Brandish as a hexadecimal value.
    • Archaic: Display as a numeric value using a primitive information blazon.
    • Integer: Display a numeric value of type Integer.

You tin create a custom format (data blazon renderer), as follows:

  1. Right-click the resource value.
  2. Select View as.
  3. Select Create. The Java Data Type Renderers dialog displays.
  4. Follow the instructions at Java Data type renderers.