Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 104 ยท Getting Started

Running, Debugging and Logcat

Run an Android app, set breakpoints, filter Logcat by tag and log level, use the Layout Inspector and Compose previews, and fix the most common build errors.

Writing code is half the job. The other half is finding out why it does not do what you meant. Android Studio gives you a small set of tools that cover almost every situation: run configurations to start the app the way you want, the debugger to stop time, Logcat to read what the app and the system say, the Layout Inspector to look at the screen's structure and Compose previews to see UI without installing anything.

All of these are features of Android Studio and a device, so the steps here are read-only walkthroughs. The runnable stand-in implements a Logcat-style filter by tag and level in plain Kotlin, because understanding how filtering works makes you much faster at using the real tool.

Running the app

At the top of Android Studio there is a run configuration drop-down, a device drop-down and the Run and Debug buttons.

  • Run installs the app and starts it normally.
  • Debug does the same with the debugger attached, so breakpoints stop execution.
  • Apply Changes pushes small code or resource edits into the running app without a full restart. Use it for quick iteration. If a change cannot be applied (for example, you changed the manifest), Studio tells you to do a full run.
  • The app run configuration has options such as the launch Activity and installation flags. The defaults are right for ordinary development.

Behind the buttons, Studio runs the same Gradle tasks you saw in Gradle for Android: build the variant selected in the Build Variants panel, install it and launch it. If the wrong variant runs, check that panel first.

The debugger

Click in the gutter next to a line number to set a breakpoint, then start the app with Debug. When execution reaches that line, the app freezes and the Debug window shows:

  • the call stack, which tells you how you got here;
  • variables in scope and their current values;
  • a place to evaluate expressions while stopped.

Controls you will use constantly:

Action What it does
Step Over Run the current line, stay in this function
Step Into Go into the function called on this line
Step Out Run until the current function returns
Resume Continue until the next breakpoint

A conditional breakpoint (right-click the red dot) stops only when an expression is true, such as note.id == 42, which is invaluable inside loops. A logging breakpoint prints a message instead of stopping, so you can trace without editing code. Debug builds are debuggable by default, release builds are not.

Breakpoints inside composable functions work, but a composable may run many times as state changes. A conditional breakpoint keeps that manageable.

Logcat

Android's system log is called logcat. The system, libraries and your app all write lines into one shared stream. Android Studio shows it in the Logcat window; adb logcat shows the same stream in a terminal.

You write to it with the Log class:

Kotlin
// read-only example: needs the Android SDK
private const val TAG = "NotesViewModel"

fun saveNote(title: String) {
    Log.d(TAG, "saveNote called with title length=${title.length}")
    if (title.isBlank()) {
        Log.w(TAG, "blank title ignored")
        return
    }
    try {
        repository.insert(title)
        Log.i(TAG, "note saved")
    } catch (e: Exception) {
        Log.e(TAG, "saving failed", e)
    }
}

Every line has a tag, a level, a time, a process id and the message. The tag names the component, and the level says how serious it is, in order from least to most:

Level Method Use
Verbose Log.v Everything, very chatty
Debug Log.d Developer diagnostics
Info Log.i Normal milestones
Warn Log.w Something odd that was handled
Error Log.e A failure; pass the exception as the third argument to get its stack trace
Assert Log.wtf "What a terrible failure": should never happen

Two practical rules. Never log secrets or personal data such as tokens and passwords; logs can be read by tools connected to the device. And remember that Debug-level lines are still printed in release builds unless you strip them, so avoid noisy or sensitive logging there.

Filtering Logcat

A real device prints thousands of lines per minute. Filtering is the skill that makes Logcat usable. In the search box of the Logcat window you can type things like:

TEXT
# read-only: Logcat filter queries
tag:NotesViewModel
level:warn
package:mine
tag:NotesViewModel level:error
message:"saving failed"

package:mine shows only your app's lines and is usually the best first filter. Combining tag: and level: narrows quickly. A crash shows up as an E line with AndroidRuntime as the tag, followed by the stack trace. Read it from the top: the first line names the exception and the following lines show where it came from, with your own package's frames usually the ones that matter.

flowchart LR
    APP["Your app<br/>Log.d / Log.e"] --> BUF["Log buffer<br/>on the device"]
    SYS["System and libraries"] --> BUF
    BUF --> ADB["adb"]
    ADB --> LC["Logcat window<br/>filters: tag, level, package"]

Everything writes to a shared buffer; filters decide which lines you see.

A stand-in for Logcat filtering

This program models a log buffer and the filter query. The real Logcat is far bigger, but the idea of matching on tag, a minimum level and a text fragment is exactly this. Notice how a minimum level means "this level and more severe", which is how level:warn behaves.

Kotlin A tiny Logcat filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Enum entries are ordered by their declaration, so e.level >= minLevel compares severity directly. That is the same trick the real log levels rely on, since they are just increasing numbers.

A stand-in for a conditional breakpoint

A breakpoint stops execution, and a conditional breakpoint stops only when an expression is true. This stand-in runs a loop and "stops" when the condition holds, printing the variables the Debug window would show. It models the logic only; the real debugger freezes the whole process and lets you step.

Kotlin A conditional breakpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Without the condition you would press Resume once per note. With it, the program stops exactly at the surprising record.

Inspecting the UI

Layout Inspector (open it from the Tools menu while the app runs) shows a live view of your screen's structure. For Compose apps it shows the composition tree: each composable, its size and position and its parameters. It can also show recomposition counts, so you can see which composables re-ran too often. This tells you why something is clipped, overlapped or the wrong size in seconds. You will return to it in Performance and Profiling.

Compose previews let you see composables inside Studio without running the app:

Kotlin
// read-only example: a preview function
@Preview(showBackground = true)
@Composable
private fun GreetingPreview() {
    Greeting(name = "Preview")
}

The preview pane renders the function, and you can pin multiple previews, switch dark mode and test different font scales. Previews work best for stateless composables, which is one more reason for the design in State Hoisting and Unidirectional Data Flow.

Inspecting network, databases and memory

Logcat shows what you print. Other tools show what the app holds and sends:

  • App Inspection (View, Tool Windows, App Inspection) in Android Studio contains the Network Inspector (every HTTP request with headers, body and timing), the Database Inspector (live Room and SQLite tables you can query and edit while the app runs) and the Background Task Inspector (WorkManager jobs and their states).
  • Layout Inspector shows the live view tree or Compose tree and the recomposition counts (see "Inspecting the UI" above).
  • Memory Profiler records allocations and heap dumps, which is how you find the object that a leak keeps alive (Performance).
  • Stetho was Facebook's library that exposed your app's network traffic, databases and SharedPreferences to the Chrome DevTools page chrome://inspect. It worked by starting a debug server inside the app (Stetho.initializeWithDefaults(this)) and, with its OkHttp interceptor, showed each request in the browser. It is in maintenance mode, because Android Studio's inspectors now do the same without extra code. You will still meet it in older projects: keep it in debugImplementation so it never ships in the release build.
  • OkHttp logging interceptor prints requests and responses to Logcat; set the level to BODY only in debug builds, since bodies can contain tokens and personal data (Retrofit basics).
  • Proxy tools (Charles, mitmproxy) show raw traffic from a device or emulator, but apps that pin certificates or ignore user-installed certificates (the default since Android 7 for apps targeting API 24+) need a debug-only network security config (Security).

Whatever you use, make debug-only tools debug-only: add them with debugImplementation, check BuildConfig.DEBUG before wiring them, and confirm the release APK does not contain them.

Common build errors

Build output goes to the Build window. Read the first error, because later ones are often consequences.

Message (roughly) Usual cause and fix
"SDK location not found" sdk.dir missing; set the path in the SDK Manager
"Could not resolve com.example:lib:1.2" Typo in the coordinates, wrong version or a missing repository such as google()
"Unresolved reference: R" The project has not synced, a resource file has an XML error or namespace is wrong
"Duplicate class ..." Two dependencies bring the same class; exclude one or align versions
"Manifest merger failed" Two manifests disagree; follow the message, often android:exported or a missing tools:replace
"Execution failed for task ':app:compileDebugKotlin'" A real Kotlin compile error is listed above this line
"Cannot access class ... check your module classpath" A dependency needed by one you use is missing from your module
App installs then crashes immediately Open Logcat, filter level:error, and read the first exception

When nothing makes sense, try File > Sync Project with Gradle Files, then Build > Clean Project. If a cache is truly corrupt, Studio offers Invalidate Caches under the File menu. Use it last, since it re-indexes everything.

With the tools covered, Getting Started is complete. In the next chapter you start building real screens, beginning with Activities and setContent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between Run and Debug in Android Studio?

    Both install and start the app. Debug also attaches the debugger, which makes breakpoints work.
  2. 2. Which Logcat level is the most severe in the normal series?

    From least to most severe: Verbose, Debug, Info, Warn, Error (and Assert). A filter on a minimum level includes that level and everything above it.
  3. 3. How do you get a stack trace into Logcat when you catch an exception?

    The Log methods accept a Throwable as the last parameter and print its stack trace.
  4. 4. Your build fails with several errors. Where should you start?

    Gradle and the compiler often report follow-on errors. Fix the first one and rebuild before judging the rest.

Summary

  • Run installs and starts the app; Debug adds the debugger; Apply Changes pushes small edits without a restart.
  • Breakpoints show the call stack and variables; conditional and logging breakpoints keep loops and repeated recompositions manageable.
  • Logcat is a shared stream; every line has a tag, a level and a message, and filters such as package:mine, tag: and level: make it usable.
  • Never log secrets, and pass the exception to Log.e to print its stack trace.
  • Layout Inspector shows the live UI tree, Compose previews render composables in Studio, and build errors should be read from the first one.

Next, start building screens in Activities and setContent.