Paramclasses Academy - Blog

Tutorials Details

←
Post 34 of 40
→

Android Studio Logcat and Debugger: Find and Fix Common Java Errors ?

Android Studio Logcat and Debugger: Find and Fix Common Java Errors ?

November 4, 2026

1. Introduction

While developing Android applications, developers frequently encounter errors such as NullPointerException, NumberFormatException, ArrayIndexOutOfBoundsException, and application crashes.

Finding the exact cause of an error is an important programming skill. Android Studio provides two powerful tools for this purpose:

  • Logcat: Displays application logs, warnings, errors, and crash information.

  • Debugger: Allows developers to pause application execution and inspect variables, objects, and program flow.

In this tutorial, we will learn how to use Logcat and the Android Studio Debugger with Java. We will also build a small calculator application and understand how to identify and fix common Java errors.

2. What Is Logcat?

Logcat is a debugging tool in Android Studio that displays real-time messages from your Android application and the Android operating system.

It helps developers:

  • Identify application crashes.

  • Read Java exception messages.

  • Display custom debugging messages.

  • Track application execution.

  • Find errors in specific classes and methods.

How to Open Logcat

  1. Open your Android Studio project.

  2. Run your application on an emulator or physical device.

  3. Open View > Tool Windows > Logcat.

  4. Select the connected device and your application process.

  5. Observe the messages displayed in the Logcat window.

When an application crashes, Logcat usually displays an exception message and a stack trace. The stack trace can contain clickable links to the source code where the error occurred.

3. Understanding Log Levels

Android provides different log levels through the android.util.Log class.

Verbose (V)

Displays detailed information, generally useful during development.

Log.v(TAG, "Verbose log message");

Debug (D)

Used to display debugging information.

Log.d(TAG, "User button clicked");

Info (I)

Used to display general informational messages.

Log.i(TAG, "Application started successfully");

Warning (W)

Used when something unexpected happens but the application can continue.

Log.w(TAG, "Username field is empty");

Error (E)

Used to report errors that need attention.

Log.e(TAG, "Unable to load user data");

Assert (A)

Android's Log.wtf() method reports an assertion-level failure for a condition that should never happen.

Log.wtf(TAG, "Unexpected application state");

The usual priority order is:

Verbose → Debug → Info → Warning → Error → Assert.

4. How to Use Log.d() in Java

Let's understand how to display custom messages in Logcat.

First, create a tag inside your Activity class:

private static final String TAG = "MainActivity";

Now add logging statements inside the onCreate() method:

Log.d(TAG, "Activity created");

Log.i(TAG, "Application is running");

Log.w(TAG, "This is a warning message");

Log.e(TAG, "This is an error message");

You can also log variable values:

int age = 22;

Log.d(TAG, "User age: " + age);

This makes it easier to understand what values your application is processing.

Important: Use meaningful tags and messages. Avoid logging passwords, authentication tokens, or other sensitive information.

5. How to Filter Messages in Logcat

A running Android device can generate thousands of log messages. Filtering helps you find the messages related to your application.

Common filtering options include:

  • Device: Select the emulator or connected Android phone.

  • Process: Select your application's running process.

  • Tag: Search messages using a particular log tag.

  • Level: Display messages at a selected severity or higher.

  • Message: Search for specific text inside log messages.

For example, the modern Logcat query field supports:

package:mine

Displays messages from packages in the currently open project.

level:ERROR

Displays Error and higher-severity messages.

tag:MainActivity

Filters messages with the specified tag.

is:crash

Finds crash-related log entries.

is:stacktrace

Finds messages that look like Java stack traces.

These queries make debugging much faster.

6. What Is the Android Studio Debugger?

The Debugger allows you to pause your application while it is running and examine what is happening inside your Java code.

You can use it to:

  • Check variable values.

  • Find incorrect calculations.

  • Understand the order in which methods execute.

  • Inspect objects and their fields.

  • Identify the exact statement causing a problem.

  • Follow the execution of your application step by step.

Logcat tells you what messages or errors were produced. The Debugger helps you investigate the program state that caused them.

7. Understanding Breakpoints

A breakpoint is a marker that tells Android Studio to pause application execution when a particular line of code is reached.

How to Add a Breakpoint

  1. Open your Java file.

  2. Find the line where you want execution to pause.

  3. Click in the left-hand gutter beside that line number.

  4. A red breakpoint marker will appear.

  5. Start your application using Debug instead of Run.

  6. Perform the action that reaches the breakpoint.

Android Studio will pause execution at that line.

Important Debugger Controls

Resume Program: Continues execution until the next breakpoint or program completion.

Step Over: Executes the current line and moves to the next line without entering a called method.

Step Into: Enters the method called on the current line.

Step Out: Completes the current method and returns to its caller.

Stop: Ends the debugging session.

These controls help you understand exactly how your application executes.

8. Inspect Variables and Watch Expressions

When execution pauses at a breakpoint, you can inspect variables in the Debug window.

For example:

int firstNumber = 20;
int secondNumber = 10;

int result = firstNumber + secondNumber;

Place a breakpoint on the result calculation.

When the debugger pauses, inspect:

firstNumber = 20
secondNumber = 10
result = not calculated yet

After using Step Over, the result becomes:

result = 30

Watches

A Watch allows you to monitor an expression while debugging.

For example:

firstNumber + secondNumber

You can also evaluate an expression using the debugger's Evaluate Expression feature.

Call Stack

The Call Stack displays the chain of method calls that led to the current execution point. It is especially useful when a method is called from multiple places.

9. Understanding Common Java Errors in Android

Let's understand some common errors that Android developers encounter.

A. NullPointerException

This exception occurs when your code tries to use an object reference that is null.

Incorrect example:

String name = null;

Log.d("MainActivity", name.length() + "");

The problem is that name does not refer to a String object.

Correct approach:

String name = null;

if (name != null) {
    Log.d("MainActivity", "Length: " + name.length());
} else {
    Log.e("MainActivity", "Name is null");
}

In Android, a NullPointerException can also occur when findViewById() returns null, for example, because the wrong layout was loaded or the requested ID does not exist in that layout.

B. ArrayIndexOutOfBoundsException

This exception occurs when you access an array using an invalid index.

Incorrect example:

int[] numbers = {10, 20, 30};

int value = numbers[5];

The array contains only three elements, so valid indexes are 0, 1, and 2.

Correct approach:

int[] numbers = {10, 20, 30};

int index = 2;

if (index >= 0 && index < numbers.length) {
    int value = numbers[index];
    Log.d("MainActivity", "Value: " + value);
}

C. NumberFormatException

This exception occurs when Java cannot convert a String into a number.

Incorrect example:

String value = "Hello";

int number = Integer.parseInt(value);

Correct approach:

String value = "100";

try {
    int number = Integer.parseInt(value);
    Log.d("MainActivity", "Number: " + number);
} catch (NumberFormatException e) {
    Log.e("MainActivity", "Invalid number", e);
}

D. ArithmeticException

This exception can occur when an integer is divided by zero.

Incorrect example:

int result = 10 / 0;

Correct approach:

int firstNumber = 10;
int secondNumber = 0;

if (secondNumber != 0) {
    int result = firstNumber / secondNumber;
} else {
    Log.e("MainActivity", "Cannot divide by zero");
}

E. Resource ID Mismatch

This problem occurs when your Java code requests a View ID that does not exist in the layout currently loaded by the Activity.

For example:

setContentView(R.layout.activity_main);

Button button = findViewById(R.id.btnSubmit);

If btnSubmit is not present in activity_main.xml, the returned reference may be null.

Always verify:

  • The correct XML layout is loaded.

  • The View ID exists in that layout.

  • The ID spelling matches.

  • The View is initialized before it is used.

F. Application Crash

An application crash happens when an uncaught exception or another fatal runtime condition stops the application.

Look for messages such as:

FATAL EXCEPTION: main
Process: com.example.myapp
java.lang.NullPointerException

Read the exception type and locate the first relevant stack-trace line that points to your own application's source code.

Do not assume that the last line of the stack trace is the cause. Framework calls may appear after the original application error.

10. Practical Project: Debugging Calculator App

Now let's create a simple calculator application using Java.

We will use this project to understand:

  • How to display Logcat messages.

  • How to add breakpoints.

  • How to inspect variable values.

  • How to validate user input.

  • How to prevent common runtime errors.

Step 1: Create a New Project

  1. Open Android Studio.

  2. Create a new project.

  3. Select Empty Views Activity.

  4. Choose Java as the programming language.

  5. Name the project DebuggingCalculatorApp.

  6. Finish project setup.

Step 2: Create the XML Layout

Open res/layout/activity_main.xml and replace its content with:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <EditText
        android:id="@+id/etFirstNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter first number"
        android:inputType="numberDecimal|numberSigned" />

    <EditText
        android:id="@+id/etSecondNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter second number"
        android:inputType="numberDecimal|numberSigned" />

    <Button
        android:id="@+id/btnCalculate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Calculate" />

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Result will appear here"
        android:textSize="20sp" />

</LinearLayout>

This layout contains two input fields, one Calculate button, and one result TextView.

Step 3: Write MainActivity.java

Open MainActivity.java and use the following code.

package com.example.debuggingcalculatorapp;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    EditText etFirstNumber, etSecondNumber;
    Button btnCalculate;
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(TAG, "Activity started");

        etFirstNumber = findViewById(R.id.etFirstNumber);
        etSecondNumber = findViewById(R.id.etSecondNumber);
        btnCalculate = findViewById(R.id.btnCalculate);
        tvResult = findViewById(R.id.tvResult);

        btnCalculate.setOnClickListener(v -> calculateResult());
    }

    private void calculateResult() {

        String firstInput = etFirstNumber.getText().toString().trim();
        String secondInput = etSecondNumber.getText().toString().trim();

        Log.d(TAG, "Calculate button clicked");

        if (firstInput.isEmpty() || secondInput.isEmpty()) {
            Toast.makeText(this,
                    "Please enter both numbers",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        try {

            double firstNumber = Double.parseDouble(firstInput);
            double secondNumber = Double.parseDouble(secondInput);

            Log.d(TAG, "First number: " + firstNumber);
            Log.d(TAG, "Second number: " + secondNumber);

            double result = firstNumber + secondNumber;

            Log.i(TAG, "Calculation successful: " + result);

            tvResult.setText("Result: " + result);

        } catch (NumberFormatException e) {

            Log.e(TAG, "Invalid number entered", e);

            Toast.makeText(this,
                    "Please enter valid numbers",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

Note: Replace the package declaration with the package name generated in your own project. The XML IDs and Java IDs must match exactly.

Step 4: Run the Application

Run your application on an emulator or Android phone.

Test the following inputs:

  • First number: 10

  • Second number: 20

Expected result:

Result: 30.0

Now leave one input field empty and click Calculate. The application should display a validation message instead of crashing.

Step 5: Check Logcat Output

Open Logcat and search for:

tag:MainActivity

You should see messages similar to:

Activity started
Calculate button clicked
First number: 10.0
Second number: 20.0
Calculation successful: 30.0

This confirms that your application is executing the expected code.

Step 6: Add a Breakpoint

Open MainActivity.java.

Find this line:

double result = firstNumber + secondNumber;

Click the gutter beside the line number to add a breakpoint.

Now:

  1. Start the application using Debug.

  2. Enter 10 and 20.

  3. Click Calculate.

  4. Android Studio will pause execution at the breakpoint.

  5. Inspect firstNumber and secondNumber in the Variables panel.

  6. Use Step Over to execute the calculation.

  7. Inspect the value of result.

  8. Click Resume Program to continue.

You have now used the Debugger to inspect a real Android application's execution.

11. How to Debug an Application Crash Step by Step

When your application crashes, follow this process:

Step 1: Open Logcat and select your application's process.

Step 2: Search for:

is:crash

Step 3: Find the exception type, such as:

java.lang.NullPointerException

Step 4: Read the exception message and locate the first relevant line from your own application in the stack trace.

Step 5: Open that source-code line and inspect the variables involved.

Step 6: Add a breakpoint if necessary and reproduce the problem.

Step 7: Fix the root cause, run the application again, and repeat the same test.

Do not simply hide an exception with an empty catch block. Understand why it occurred and correct the underlying problem.

12. Best Practices for Debugging Android Applications

  • Use meaningful Logcat tags.

  • Use the appropriate log level.

  • Avoid logging sensitive user information.

  • Add breakpoints near suspicious code.

  • Inspect variable values before changing code.

  • Read the complete relevant stack trace.

  • Validate user input before processing it.

  • Remove unnecessary debugging messages before release.

  • Test the application after fixing each issue.

  • Avoid running long operations on the Android main thread.

13. Conclusion

Logcat and Debugger are essential tools for Android developers.

Logcat helps us read application messages, warnings, and exceptions. The Debugger helps us pause execution, inspect variables, follow method calls, and understand the actual cause of a problem.

By practising both tools, you can identify Java errors faster, fix application crashes, and develop more reliable Android applications.

14. Frequently Asked Questions

Q1. What is Logcat in Android Studio?

Logcat is a tool that displays real-time application logs, system messages, warnings, and errors.

Q2. What is the difference between Run and Debug?

Run starts the application normally. Debug starts the application with debugging support, allowing you to use breakpoints and inspect program execution.

Q3. What is a breakpoint?

A breakpoint is a marker that pauses application execution at a selected line of code.

Q4. What does NullPointerException mean?

It means your code tried to use an object reference that does not refer to an actual object.

Q5. How can I find an application crash in Logcat?

Use the is:crash query, identify the exception type, and inspect the relevant stack-trace line from your application.

Q6. Can I debug an application on a real Android phone?

Yes. Connect your phone with USB debugging enabled, select it as the deployment device, and start the application using Debug.

Q7. Why should developers use Log.d()?

Log.d() helps developers display useful debugging information, such as variable values and application execution events.

←
Post 34 of 40
→