Как посмотреть ошибки в android studio

I want to know how to show compilation errors in Android Studio. I tried the following one:

Android Studio: Where is the Compiler Error Output Window?

But it is showing another error:

javac: invalid target release: 1.8

Anybody who knows the actual solution please reply.

Suragch's user avatar

Suragch

477k306 gold badges1359 silver badges1386 bronze badges

asked Jun 22, 2013 at 16:29

iamcrypticcoder's user avatar

iamcrypticcoderiamcrypticcoder

2,4994 gold badges27 silver badges49 bronze badges

There is a ‘Problems’ view in the project window:

Project window - click on drop down and select 'Problems'

Just click on the drop down (Android setting is default) and select ‘Problems’. Not comparable to eclipse problems view tough…

answered Feb 26, 2016 at 13:18

Lonzak's user avatar

4

Using F2

In addition to what the other answers say, you can find errors by pressing F2 or Shift+F2. This is useful when you can’t see the where the red indicator is on the side bar.

enter image description here

Community's user avatar

answered Jul 12, 2018 at 3:47

Suragch's user avatar

SuragchSuragch

477k306 gold badges1359 silver badges1386 bronze badges

1

There’s «Messages» tab in Android Studio. Complilation errors and warning go there. You can select it by pressing alt+0 (⌘+0 in OS X — a shortcut to View|Tool Windows|Messages).

Geeks On Hugs's user avatar

answered Jun 22, 2013 at 16:43

ernazm's user avatar

ernazmernazm

9,2084 gold badges44 silver badges51 bronze badges

6

I was looking for the «Problems» view that you can see in Eclipse when building projects. For that, you can go to Analyze -> Inspect Code

Where is the warnings view in Android Studio?

and then I clicked on «Group by Severity» so that I could see the warnings and errors.

Community's user avatar

answered Mar 26, 2015 at 0:30

Lou Morda's user avatar

Lou MordaLou Morda

5,0682 gold badges43 silver badges49 bronze badges

In the toolbar, go to Analyze -> Inspect Code

After That, you will have the Inspection Results window with the detailed errors and warnings. see image:

The Inspection Results window

answered Jul 31, 2018 at 11:37

Hesham Yassin's user avatar

Hesham YassinHesham Yassin

4,2912 gold badges21 silver badges23 bronze badges

1

Next / Previous highlighted error: F2/Shift + F2

Show descriptions of error at caret: Ctrl+F1

answered Feb 16, 2021 at 13:27

Manishoaham's user avatar

ManishoahamManishoaham

6011 gold badge5 silver badges14 bronze badges

Приготовьте отладчик! Пишем приложение с ошибками, затем учимся их находить и дебажить

https://gbcdn.mrgcdn.ru/uploads/post/2735/og_image/ce05da5c8c8f97a3bf7713b7cbaf3802.png

Иногда в приложении встречаются ошибки, которые нельзя увидеть даже после запуска. Например, код компилируется, проект запускается, но результат далёк от желаемого: приложение падает или вдруг появляется какая-то ошибка (баг). В таких случаях приходится «запасаться логами», «брать в руки отладчик» и искать ошибки.

Часто процесс поиска и исправления бага состоит из трёх шагов:

  1. Воспроизведение ошибки — вы понимаете, какие действия нужно сделать в приложении, чтобы повторить ошибку.
  2. Поиск места ошибки — определяете класс и метод, в котором ошибка происходит.
  3. Исправление ошибки.

Если приложение не падает и чтение логов ничего не даёт, то найти точное место ошибки в коде помогает дебаггер (отладчик) — инструмент среды разработки.

    Чтобы посмотреть на логи и воспользоваться дебаггером, давайте напишем простое тестовое (и заведомо неправильное) приложение, которое даст нам все возможности для поиска ошибок.

    Это будет приложение, которое сравнивает два числа. Если числа равны, то будет выводиться результат «Равно», и наоборот. Начнём с простых шагов:

  1. Открываем Android Studio. 
  2. Создаём проект с шаблоном Empty Activity. 
  3. Выбираем язык Java, так как его, как правило, знают больше людей, чем Kotlin. 

Нам автоматически откроются две вкладки: activity_main.xml и MainActivity.java. Сначала нарисуем макет: просто замените всё, что есть в activity_main.xml, на код ниже:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">
 
  <EditText
     android:id="@+id/first_number_et"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:ems="10"
     android:gravity="center"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toTopOf="parent" />
 
  <EditText
     android:id="@+id/second_number_et"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:ems="10"
     android:gravity="center"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toBottomOf="@+id/first_number_et" />
 
  <Button
     android:id="@+id/button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Равно?"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toBottomOf="@+id/second_number_et" />
 
  <TextView
     android:id="@+id/answer_tv"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text=""
     android:textSize="32sp"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>

Можете запустить проект и посмотреть, что получилось:

Теперь оживим наше приложение. Скопируйте в MainActivity этот код:

public class MainActivity extends AppCompatActivity {
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
 
     final Button button = (Button) findViewById(R.id.button);
     final EditText first = (EditText) findViewById(R.id.first_number_et);
     final EditText second = (EditText) findViewById(R.id.second_number_et);
     final TextView answer = (TextView) findViewById(R.id.answer_tv);
 
     button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Integer firstInt = Integer.parseInt(first.getText().toString());
           Integer secondInt = Integer.parseInt(second.getText().toString());
           if (firstInt == secondInt) {
              answer.setText("Равно");
           } else {
              answer.setText("Равно");
           }
        }
     });
  }
}

В этом коде всё просто: 

  1. Находим поля ввода, поле с текстом и кнопку.
  2. Вешаем на кнопку слушатель нажатий.
  3. По нажатию на кнопку получаем числа из полей ввода и сравниваем их.
  4. В зависимости от результата выводим «Равно» или «Не равно».

Запустим приложение и введём буквы вместо чисел:

Нажмём на кнопку, и приложение упадёт! Время читать логи. Открываем внизу слева вкладку «6: Logcat» и видим:

Читать логи просто: нужно найти красный текст и прочитать сообщение системы. В нашем случае это java.lang.NumberFormatException: For input string: «f». Указан тип ошибки NumberFormatException, который говорит, что возникла какая-то проблема с форматированием числа. И дополнение: For input string: «f». Введено “f”. Уже можно догадаться, что программа ждёт число, а мы передаём ей символ. Далее в красном тексте видно и ссылку на проблемную строку: at com.example.appdebugging.MainActivity$1.onClick(MainActivity.java:26). Проблема в методе onClick класса MainActivity, строка 24. Можно просто кликнуть по ссылке и перейти на указанную строку:

int firstInt = Integer.parseInt(first.getText().toString());

Конечно, метод parseInt может принимать только числовые значения, но никак не буквенные! Даже в его описании это сказано — и мы можем увидеть, какой тип ошибки этот метод выбрасывает (NumberFormatException).

Здесь мы привели один из примеров. Типов ошибок может быть огромное количество, все мы рассматривать не будем. Но все ошибки в Logcat’е указываются по похожему принципу: 

  • красный текст;
  • тип ошибки — в нашем случае это NumberFormatException;
  • пояснение — у нас это For input string: «f»;
  • ссылка на строку, на которой произошла ошибка — здесь видим MainActivity.java:26. 

Исправим эту ошибку и обезопасим себя от некорректного ввода. Добавим в наши поля ввода android:inputType=»number», а остальной код оставим без изменений:

...
<EditText
  android:id="@+id/first_number_et"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:ems="10"
  android:gravity="center"
  android:inputType="number"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent" />
 
<EditText
  android:id="@+id/second_number_et"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:ems="10"
  android:gravity="center"
  android:inputType="number"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toBottomOf="@+id/first_number_et" />
...

    Теперь можем вводить только числа. Проверим, как работает равенство: введём одинаковые числа в оба поля. Всё в порядке:

На равенство проверили. Введём разные числа: 

Тоже равно. То есть приложение работает, ничего не падает, но результат не совсем тот, который требуется. Наверняка вы и без дебаггинга догадались, в чём ошибка, потому что приложение очень простое, всего несколько строк кода. Но такие же проблемы возникают в приложениях и на миллион строк. Поэтому пройдём по уже известным нам этапам дебаггинга:

  1. Воспроизведём ошибку: да, ошибка воспроизводится стабильно с любыми двумя разными числами.
  2. Подумаем, где может быть ошибка: наверняка там, где сравниваются числа. Туда и будем смотреть.
  3. Исправим ошибку: сначала найдём её с помощью дебаггера, а когда поймём, в чём проблема, — будем исправлять.

И здесь на помощь приходит отладчик. Для начала поставим точки останова сразу в трёх местах:

    Чтобы поставить или снять точку останова, достаточно кликнуть левой кнопкой мыши справа от номера строки или поставить курсор на нужную строку, а затем нажать CTRL+F8. Почему мы хотим остановить программу именно там? Чтобы посмотреть, правильные ли числа сравниваются, а затем определить, в какую ветку в нашем ветвлении заходит программа дальше. Запускаем программу с помощью сочетания клавиш SHIFT+F9 или нажимаем на кнопку с жучком:

  

    Появится дополнительное окно, в котором нужно выбрать ваш девайс и приложение:

Вы в режиме дебага. Обратите внимание на две вещи:

  1. Точки останова теперь помечены галочками. Это значит, что вы находитесь на экране, где стоят эти точки, и что дебаггер готов к работе.
  2. Открылось окно дебага внизу: вкладка «5: Debug». В нём будет отображаться необходимая вам информация.

    Введём неравные числа и нажмём кнопку «РАВНО?». Программа остановилась на первой точке:

Давайте разбираться:

  1. Сразу подсвечивается синим строка, где программа остановлена: в окне кода на 28-й строке и в левом окне отладчика (там даже можно увидеть, какой метод вызван, — onClick).
  2. В правом, основном окне отладчика, всё гораздо интереснее. Здесь можно увидеть инстансы наших вью (answer, first, second), в конце которых серым текстом даже отображаются их id. Но интереснее всего посмотреть на firstInt и secondInt. Там записаны значения, которые мы сейчас будем сравнивать.

Как видим, значения именно такие, какие мы и ввели. Значит, проблема не в получении чисел из полей. Давайте двигаться дальше — нам нужно посмотреть, в правильную ли ветку мы заходим. Для этого можно нажать F8 (перейти на следующую строку выполнения кода). А если следующая точка останова далеко или в другом классе, можно нажать F9 — программа просто возобновит работу и остановится на следующей точке. В интерфейсе эти кнопки находятся здесь:

Остановить дебаггер, если он больше не нужен, можно через CTRL+F2 или кнопку «Стоп»:

    В нашем случае неважно, какую кнопку нажимать (F9 или F8). Мы сразу переходим к следующей точке останова программы:

Ветка правильная, то есть логика программы верна, числа firstInt и secondInt не изменились. Зато мы сразу видим, что подпись некорректная! Вот в чём была ошибка. Исправим подпись и проверим программу ещё раз.

    Мы уже починили два бага: падение приложения с помощью логов и некорректную логику (с помощью отладчика). Хеппи пас (happy path) пройден. То есть основная функциональность при корректных данных работает. Но нам надо проверить не только хеппи пас — пользователь может ввести что угодно. И программа может нормально работать в большинстве случаев, но вести себя странно в специфических состояниях. Давайте введём числа побольше и посмотрим, что будет:

Не сработало — программа хочет сказать, что 1000 не равна 1000, но это абсурд. Запускаем приложение в режиме отладки. Точка останова уже есть. Смотрим в отладчик:

Числа одинаковые, что могло пойти не так? Обращаем внимание на тип переменной — Integer. Так вот в чём проблема! Это не примитивный тип данных, а ссылочный. Ссылочные типы нельзя сравнивать через ==, потому что будут сравниваться ссылки объектов, а не они сами. Но для Integer в Java есть нюанс: Integer может кешироваться до 127, и если мы вводим по единице в оба поля числа до 127, то фактически сравниваем просто int. А если вводим больше, то получаем два разных объекта. Адреса у объектов не совпадают, а именно так Java сравнивает их.

Есть два решения проблемы:

  1. Изменить тип Integer на примитив int.
  2. Сравнивать как объекты.

    Не рекомендуется менять тип этих полей в реальном приложении: числа могут приходить извне, и тип лучше оставлять прежним. Изменим то, как мы сравниваем числа:

if (firstInt.equals(secondInt)) {
  answer.setText("Равно");
} else {
  answer.setText("Не равно");
}

Проверяем:

Всё работает. Наконец-то! Хотя… Давайте посмотрим, что будет, если пользователь ничего не введёт, но нажмёт на кнопку? Приложение опять упало… Смотрим в логи:

Опять NumberFormatException, при этом строка пустая. Давайте поставим точку останова на 26-й строке и заглянем с помощью отладчика глубже.

Нажмём F8 — и перейдём в глубины операционной системы:

    Интересно! Давайте обернём код в try/catch и посмотрим ошибке в лицо. Если что, поправим приложение. Выделяем код внутри метода onClick() и нажимаем Ctrl+Alt+T:

Выбираем try / catch, среда разработки сама допишет код. Поставим точку останова. Получим:

Запускаем приложение и ловим ошибку:

Действительно, как и в логах, — NumberFormatException. Метод parseInt выбрасывает исключение, если в него передать пустую строку. Как обрабатывать такую проблему — решать исключительно вам. Два самых простых способа:

  1. Проверять получаемые строки first.getText().toString() и second.getText().toString() на пустые значения. И если хоть одно значение пустое — говорить об этом пользователю и не вызывать метод parseInt.
  2. Или использовать уже готовую конструкцию try / catch:

Теперь-то точно всё в порядке! Хотя профессиональным тестировщикам это приложение никто не отдавал: поищете ещё ошибки? :)

Ошибки в Android приложениях — неотъемлемая часть любой разработки, то насколько быстро разработчик находит баг влияет на скорость создания мобильного приложения, а то, насколько точно получается локализовать проблему — на качество конечного продукта. Давайте рассмотрим подходы и инструменты, которые помогают при дебаге.

ADB = Android Debug Bridge

Все общение с подключенным устройством или эмулятором происходит через утилиту командной строки ADB (Android Debug Bridge) — данный инструмент входит в Android SDK и скачать его можно на официальной странице.

Debugger в Android Studio

Посмотреть как программа себя ведет по шагам, какие значения принимают переменные и т.д. позволяет debugger, встроенный в среду разработки Android Studio.

Что такое Stacktrace

Stacktrace — это последовательность вызовов, которая привела до определенного момента в коде. Когда приложение крэшится, то, чтобы понять почему это произошло, зачастую, достаточно открыть Logcat и посмотреть stacktrace. В нем будет информация, что, где и почему упало.

StackTrace в Android StudioВ данном примере видно, что на 63 строке в классе SingleBankConnectedFragment произошел IllegalStateException.

StackTrace и Proguard

Важное замечание — если вы обфусцировали ваше приложение и оно упало уже после этого, то логи читать чуть чуть сложнее. Есть и хорошая новость — при сборке приложения создается mapping файл, в котором указывается какие классы как стали называться. В Google play developer console например можно этот файл даже загрузить, чтобы расшифровка логов происходила автоматически.

Breakpoint

Breakpoint, или по-русски «Точка останова» — флаг, устанавливающийся на определенную строчку-инструкцию в программе. Она говорит, что в этом месте исполнение приложения надо поставить на паузу. После этого разработчик сможет посмотреть значения переменных в данный момент для поиска багов. Далее надо решить — пойти ли дальше по шагам, зайти ли внутрь очередной функции или просто возобновить исполнение.

Для того, чтобы установить Breakpoint достаточно нажать на область рядом с номером строки

Debug ошибок в андроид приложениях

Чтобы запустить программу в debug режиме, есть специальная кнопка в панели Android studio

Debug ошибок в андроид приложениях

Также можно подключиться к уже выполняющемуся процессу

Debug ошибок в андроид приложениях

Когда процесс остановится в указанной точке можно перейти к следующей инструкции (строчке в программе). Также можно зайти внутрь функции, если в данный момент времени находимся на строчке ее вызова.

Debug ошибок в андроид приложениях

Вычисление значений на лету

В режиме дебага, находясь на определенной строке можно посмотреть состояние программы в данный момент. То, какие переменные какие значения принимают.

Debug ошибок в андроид приложениях

Также можно произвести любые вычисления в данном контексте

Debug ошибок в андроид приложениях

Подмена значений переменных на лету

Иногда полезно подменить значение переменной прямо на лету. Например, когда отображение в интерфейсе зависит от переменной. Тогда удобно, не перекомпилируя приложение или изменяя значения в базе данных, посмотреть как будет выглядеть UI при разных значениях. Это можно сделать прямо из окна мониторинга переменных

Debug ошибок в андроид приложениях

Условный Breakpoint

Не всегда необходимо всегда останавливать выполнение программы на определенной строке. К примеру, если хотим продебажить тело цикла, в котором много итераций и нам интересна только та, на которой выполняется определенное условие. Для таких целей точке останова можно задать условие:

Debug ошибок в андроид приложениях

программа остановится, только если выполнится условие для данного Breakpoint.

Layout inspector в Android Studio для дебага View

В Android Studio есть одна очень полезная вещь для дебага — Layout inspector. Он позволяет просмотреть UI открытой активности к разрезе отдельных View. Это бывает удобно, особенно если

  • Необходимо отдебажить код, связанный с определенным интерфейсом — можно быстро найти нужные id view и перейти в IDE в нужный участок кода,
  • Проблема связана с отображением интерфейса — можно посмотреть где какие элементы располагаются, что мешают друг другу и тд.

Layout inspector вызывается из меню Tools -> Layout inspector

Debug ошибок в андроид приложениях

Инструмент позволяет прямо в Android studio видеть элементы интерфейса запущенного Android приложения, посмотреть свойства отдельно взятого View и увидеть целиком иерархию конкретно взятого интерфейса

Debug ошибок в андроид приложениях

Логи как средство для дебага

Когда дело касается порядка вызова методов, особенно когда методы асинхронные, бегать по коду в режиме дебага не удобно. Тогда на помощь приходят логи и android logcat. Инструмент, позволяющий получить логи из android приложения.

Разместив вывод в лог в интересующих методах можно наблюдать порядок их вызова.

Hint: для удобства и ускорения работы с логами, можно использовать Live template в Android Studio

Мой шаблон для расстановки логов с именем logs выглядит так

Log.e("!@#", "$package$.$method$:$line$");

Вывод в канал ошибок лога с тэгом !@#, что позволяет легко его отфильтровать и сообщением, которое содержит имя пакета, класс и строку.

Находясь на нужной строчке остается нажать Ctrl + J (вызов диалога добавления шаблона), написать logs и нажать Enter

Debug ошибок в андроид приложениях

И IDE сама добавит строку, вида

Log.e("!@#", "com.package.test.MyActivity:64");

Сетевой мониторинг

Когда дело доходит до взаимодействия с сервером, не всегда ошибка на стороне клиента. В процессе разработки всегда стоит включать логирование сетевый запросов и ответов в Logcat.

Okhttp

Okhttp — популярный HTTP клиент, который позволяет включить логирование сетевых запросов практически из коробки.

Добавляем в проект библиотеку logging-interceptor

implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'

и при конфигурировании Okhttp клиента добавляем нужный interceptor, а для того, чтобы логи не попали в релизную версию наверняка, условием добавления логирования сетевых запросов можно определить как сборка Debug версии приложения

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
  builder.addInterceptor(logging);
}
OkHttpClient client = builder.build();

Retrofit

Retrofit часто используется при создании клиент-серверных приложений. Для того, чтобы включить логирование сетевых запросов, достаточно лишь указать клиентом в Retrofit Okhttp, настроенный как описано выше

builder.client(okHttpClient);

Fiddler, Charles и другие прокси

Отследить сетевой траффик также можно с помощью специализированных программ, проксирующие через себя траффик мобильного приложения, например такие как Fiddler, Charles и другие.

Debug обфусцированного кода

При дебаге кода после обфускации надо помнить, что номера строк и имена методов не совпадают с тем, что вы видите в исходниках. При сборке будет создан map file, который поможет соотнести stracktrace в продакшене с вашим кодом.

Вы теперь в курсе как отладить приложение. Время узнать какие полезные инструменты есть для его создания.

With Eclipse, stack trace was printed out in Logcat so I could trace where exactly in my application the exception occurred. However, with Android Studio the exception gets neatly parsed in a window but I cannot find the source line and file.

I tried exploring «stackState» (see below) but didn’t find any clue.

How are you supposed to find it?

enter image description here

asked Nov 12, 2015 at 22:54

c0dehunter's user avatar

c0dehunterc0dehunter

6,36216 gold badges76 silver badges139 bronze badges

1

The LogCat in Android Studio will show the same info as Eclipse

You can show the window with: Alt+6 or Cmd+6 in Mac.

With Ctrl+Shift+F8 enable «View Breakpoints…»
and check if inside if the option: «Java Exception Breakpoints» is disabled!
enter image description here

Read the documents from the official documentation:

Reading and writing Logs

Debugging with Android Studio

answered Nov 12, 2015 at 23:29

Jorgesys's user avatar

With Eclipse, stack trace was printed out in Logcat so I could trace where exactly in my application the exception occurred.

It does that too, in Android Studio, in the Android Monitor view (docked on the bottom of your screen).

However, with Android Studio the exception gets neatly parsed in a window but I cannot find the source line and file.

I suspect that’s because you have Android Studio’s debugger set up to break on exceptions. I haven’t used that, but if it works the way Eclipse’s equivalent feature worked, the exception will not show up in LogCat, because it hasn’t gotten there yet, courtesy of the debugger.

answered Nov 12, 2015 at 22:56

CommonsWare's user avatar

CommonsWareCommonsWare

982k189 gold badges2383 silver badges2466 bronze badges

Overview

When building Android apps, your app is bound to crash from time to time or exhibit strange unexpected behavior. You know you have experienced a runtime exception when you see this in your emulator or device:

Don’t worry though! This is totally normal and there’s a specific set of steps you can take to solve these. Refer to our guide below and/or these debugging slides for more a detailed look at debugging crashes and investigating unexpected problems with your app.

Debugging Mindset

As an Android developer, you’ll need to cultivate a «debugging mindset» as well as build up defensive programming practices that make writing error-prone code less likely. In addition, you’ll often find yourself in the role of a coding investigator in order to understand where and why an app is crashing or not working as expected. A few key principles about debugging are captured below:

  • Just because a program runs, doesn’t mean it’s going to work as you expected. This class of issues are known as runtime errors. This is contrast to compile-time errors which prevent an app from running and are often easier to catch.
  • Think of debugging as an opportunity to fill gaps in knowledge. Debugging is an opportunity to understand your app better than you did before and hopefully sharpen your ability to write correct code in the future by programming defensively.
  • Debugging is a vital part of the software development process. Often you may find yourself on some days spending more time debugging crashes or unexpected behavior then writing new code. This is entirely normal as a mobile engineer.

Debugging Principles

The following high-level principles should be applied when faced with an unexpected app behavior during investigation:

  • Replicate. Convince yourself that there is an issue in the code that can be repeatedly reproduced by following the same steps. Before assuming the code is broken, try restarting the emulator, trying the app on a device and/or fully re-building the app.
  • Reduce. Try to isolate or reduce the code surrounding the issue and figure out the simplest way to reproduce what’s occurring. Comment out or remove extraneous code that could be complicating the issue.
  • Research. If you are running into a major unexpected issue, you are probably not alone. Search Google for the behavior using any descriptive identifiers. Visit the issue tracker for the component you are seeing issues with. Search stackoverflow for posts about the same issue.

Armed with this mindset and the above principles, let’s take a look at how to debug and investigate issues that arise within our apps.

Debugging Procedure

When you see your app crash and close, the basic steps for diagnosing and resolving this are outlined below:

  1. Find the final exception stack trace within the Android Monitor (logcat)
  2. Identify the exception type, message, and file with line number
  3. Open the file within your app and find the line number
  4. Look at the exception type and message to diagnose the problem
  5. If the problem is not familiar, google around searching for answers
  6. Make fixes based on the proposed solutions and re-run the app
  7. Repeat until the crash no longer occurs

This process nearly always starts with an unexpected app crash as we’ll see below.

Witnessing the Crash

Suppose we were building a simple movie trailer app called Flixster that lets the users browse new movies and watch trailers from Youtube. Imagine we ran the app, and we wanted to play the trailer and we saw this crash instead:

First off though when you see the crash dialog, don’t press OK on that dialog until after you’ve already went through these steps below to identify the stacktrace details.

Setting Up Error Filter

First, within Android Studio, be sure to setup your Android Monitor to filter for «Errors» only to reduce noise:

  1. Select «Error» as the log level to display
  2. Select «Show only selected application» to filter messages

This will set you up to see only serious issues as they come up.

Note: See this blog post for improving the coloring of errors or logs in LogCat and for other related tools.

Find the Stack Trace

Now let’s go into Android Studio and select open up the «Android Monitor». Expand the 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 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.
  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 them 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 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.codepath.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.

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 problem:

  1. File name
  2. Line number
  3. Exception type
  4. Exception message

Consider the exception we copied above:

This exception needs to be translated to identifying the following elements:

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

Open the Offending File

Next, we need to open up the offending file and line number. In this case, the VideoActivity.java to line 13 which looks like this:

public class VideoActivity extends YouTubeBaseActivity{
    // -----> LINE 13 is immediately below <--------
    String videoKey = getIntent().getStringExtra("video_key");

    // ...
    protected void onCreate(Bundle savedInstanceState) {
       // ....
    }
}

Therefore, we know the crash is happening on line 13:

String videoKey = getIntent().getStringExtra("video_key");

This is a great first step to now solving the problem because we know exactly where the exception is being triggered.

Diagnose the Problem

Next, we need to use the exception type and message to diagnose the problem at that line. The type in this case is java.lang.NullPointerException and the message was Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference.

The type is the most important part because there are a limited number of types. If the type is java.lang.NullPointerException then we know 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.

The message above gives you the specifics that the method getStringExtra is being called on a null object. This tell us that getIntent() is actually null since this is the object getStringExtra is being called on. That might seem strange, why is the getIntent() null here? How do we fix this?

Google for the Exception

Often we won’t know what is going wrong even after we’ve diagnosed the issue. We know that «getIntent() is null and shouldn’t be». But we don’t know why or how to fix.

At this stage, we need to google cleverly for the solution. Any problem you have, stackoverflow probably has the answer. We need to identify a search query that is likely to find us answers. The recipe is generally a query like android [exception type] [partial exception message]. The type in this case is java.lang.NullPointerException and the message was Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference.

We might start by googling: android java.lang.NullPointerException android.content.Intent.getStringExtra(java.lang.String). These results get returned.

You generally want to look for «stackoverflow» links but in this case, the first result is this other forum.

Scroll to the bottom and you will find this message by the original author:

I realize my mistake now. I was calling the getIntent() method outside of the onCreate method.
As soon as I moved the code calling getIntent() inside the onCreate method it’s all working fine.

Let’s give this solution a try! He seems to suggest the issue is that getIntent() is being called outside of the onCreate block and we need to move it inside that method.

Address the Problem

Based on the advice given on stackoverflow or other sites from Google, we can then apply a potential fix. In this case, the VideoActivity.java can then be changed to:

public class VideoActivity extends YouTubeBaseActivity{
    // ...move the call into the onCreate block
    String videoKey; // declare here
    protected void onCreate(Bundle savedInstanceState) {
       // ....
       // set the value inside the block
       videoKey = getIntent().getStringExtra("video_key");
    }
}

Now, we can run the app and see if things work as expected!

Verify the Error is Fixed

Let’s re-run the app and try this out again:

Great! The exception seems to have been fixed!

Rinse and Repeat

Sometimes the first fix we try after googling doesn’t work. Or it makes things worse. Sometimes the solutions are wrong. Sometimes we have to try different queries. Here’s a few guidelines:

  • It’s normal to have to try 3-4 solutions before one actually works.
  • Try to stick with stackoverflow results from Google first
  • Open up multiple stackoverflow pages and look for answers you see repeated multiple times
  • Look for stackoverflow answers that have a green check mark and many upvotes.

Don’t get discouraged! Look through a handful of sites and you are bound to find the solution in 80% of cases as long as you have the right query. Try multiple variations of your query until you find the right solution.

In certain cases, we need to investigate the problem further. The methods for investigating why something is broken are outlined below.

Investigation Methodologies

In addition to finding and googling errors, often additional methods have to be applied to figure out what is going wrong. This usually becomes helpful when something isn’t as we expected in the app and we need to figure out why. The three most common investigation techniques in Android are:

  1. Toasts — Using toasts to alert us to failures
  2. Logging — Using the logging system to print out values
  3. Breakpoints — Using the breakpoint system to investigate values

Both methods are intended for us to be able to determine why a value isn’t as we expect. Let’s take a look at how to use each.

Let’s start with the same app from above and suppose we are trying to get the app so that when the image at the top of the movie details page is clicked, then the movie trailer begins playing.

public class InfoActivity extends YouTubeBaseActivity {
    private ImageView backdropTrailer;
    private String videoKey;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        // ...
        backdropTrailer = (ImageView) findViewById(R.id.ivPoster);
        // Trigger video when image is clicked
        backdropTrailer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 
                // Launch youtube video with key if not null
                if (videoKey != null) {
                    Intent i = new Intent(InfoActivity.this, VideoActivity.class);
                    i.putExtra("videoKey", videoKey);
                    startActivity(i);
                }
            }
        });
    }
}

Unfortunately when testing, we see that the trailer does not come up as expected when we run the app and click the top image:

Why doesn’t the video launch when you click on the image as expected? Let’s investigate.

Notifying Failure with Toasts

The video activity isn’t launching when the user presses the image but let’s see if we can narrow down the problem. First, let’s add a toast message to make sure we can begin to understand the issue. Toasts are messages that popup within the app. For example:

Toast.makeText(this, "Message saved as draft.", Toast.LENGTH_SHORT).show();

would produce:

Toast

In InfoActivity.java, we will add the following toast message inside the onClick listener method:

public class InfoActivity extends YouTubeBaseActivity {
    // ...
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        // ...
        backdropTrailer = (ImageView) findViewById(R.id.ivPoster);
        backdropTrailer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 
                // Launch youtube video with key if not null
                if (videoKey != null) {
                    Intent i = new Intent(InfoActivity.this, VideoActivity.class);
                    i.putExtra("videoKey", videoKey);
                    startActivity(i);
                } else {
                    // ----> ADD A TOAST HERE. This means video key is null
                    Toast.makeText(InfoActivity.this, "The key is null!", Toast.LENGTH_SHORT).show();
                } 
            }
        });
    }
}

With the toast added, running this again, we see the problem is confirmed:

The problem is that the youtube video key is null where as it should have a value. We haven’t fixed the problem, but we at least know what the initial issue is.

Using a toast message we can easily notify ourselves when something goes wrong in our app. We don’t even have to check the logs. Be sure to add toasts whenever there are failure cases for networking, intents, persistence, etc so you can easily spot when things go wrong.

Investigating using Logging

Next, let’s fix the problem the toast clarified for us. We now know the problem is that the youtube video key is null where as it should have a value. Let’s take a look at the method that fetches the video key for us:

public void fetchMovies(int videoId) {
    // URL should be: https://api.themoviedb.org/3/movie/246655/videos?api_key=KEY
    String url = "https://api.themoviedb.org/3/movie" + movie_id + "/videos?api_key=" + KEY;
    client.get(url, new JsonHttpResponseHandler(){
        @Override
        public void onSuccess(int statusCode, Headers headers, JSON response) {
            JSONArray movieJsonResults = null;
            try {
                movieJsonResults = response.getJSONArray("results");
                JSONObject result = movieJsonResults.getJSONObject(0);
                // Get the key from the JSON
                videoKey = result.getString("key");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

This method is somehow not fetching the key that we’d expect. Let’s start by logging inside the onSuccess method to see if we are getting inside there as we expect.

The Android logger is pretty easy to use. The log options are as follows:

Level  Method
Verbose Log.v()
Debug Log.d()
Info Log.i()
Warn Log.w()
Error Log.e()

They are sorted by relevance with Log.i() being the least important one. The first parameter of these methods is the category string (can be any label we choose) and the second is the actual message to display.

We can use the logger by adding two lines to the code: one at the top before the network call and one inside onSuccess to see if they both display:

Log.e("VIDEOS", "HELLO"); // <------------ LOGGING
client.get(url, new JsonHttpResponseHandler(){
    @Override
    public void onSuccess(int statusCode, Headers headers, JSON response) {
        JSONArray movieJsonResults = null;
        try {
            // LOG the entire JSON response string below
            Log.e("VIDEOS", response.toString()); // <------------ LOGGING
            movieJsonResults = response.getJSONArray("results");
            JSONObject result = movieJsonResults.getJSONObject(0);
            videoKey = result.getString("key");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
});

When running the app, the first log does show up as expected but the one inside onSuccess does not show up at all in the Android monitor:

Notice that we see HELLO but no other line logs. This means that we now know that the onSuccess method is never called. This means our network request sent out is failing for some reason. We are one step closer to fixing this issue.

Investigating using Breakpoints

In order to investigate why the network request sent out is failing, we are going to bring out the most powerful debugging tool we have which is the breakpointing engine in Android Studio which allows us to stop the app and investigate our environment thoroughly.

First, we have to decide at which points we want to stop the app and investigate. This is done by setting breakpoints. Let’s set two breakpoints to investigate the network request:

Now, we need to run the app using the «debugger» rather than the normal run command:

Once the debugger connects, we can click on the movie to trigger the code to run. Once the code hits the spot with a breakpoint, the entire code pauses and let’s us inspect everything:

Here we were able to inspect the URL and compare the URL against the expected value. Our actual URL was «https://api.themoviedb.org/3/movie246655/videos?api_key=KEY» while the expected URL was «https://api.themoviedb.org/3/movie/246655/videos?api_key=KEY». Extremely subtle difference. Can you spot it?

Then we can hit «resume» () to continue until the next breakpoint or stop debugging () to end the session.

Breakpoints are incredibly powerful and worthy of additional investigation. To learn more about breakpoints, check out this official Android Guide on debugging and this third-party breakpoints guide.

Fixing the Issue

Now that we know the issue is the URL being incorrectly formed, we can fix that in the original code in InfoActivity.java:

public void fetchMovies(int videoId) {
    // ADD trailing slash to the URL to fix the issue
    String url = "https://api.themoviedb.org/3/movie/" + // <----- add trailing slash
       movie_id + "/videos?api_key=" + KEY;
    client.get(url, new JsonHttpResponseHandler(){ 
      // ...same as before...
    });
}    

and remove any old log statements we don’t need. Now, we can try running the app again:

Great! The video now plays exactly as expected!

Wrapping Up

In this section, we looked at three important ways to investigate your application:

  1. Toasts — Display messages inside the app emulator. Good for notifying you of common failure cases.
  2. Logs — Display messages in the Android monitor. Good to printing out values and seeing if code is running.
  3. Breakpoints — Halt execution of your code with breakpoints and inspect the entire environment to figure out which values are incorrect or what code hasn’t run.

With these tools and the power of Google, you should be well-equipped to debug any errors or issues that come up as you are developing your apps. Good luck!

References

  • http://andressjsu.blogspot.com/2016/07/android-debugging.html
  • https://developer.android.com/studio/debug/index.html
  • http://blog.strv.com/debugging-in-android-studio-as/
  • https://www.youtube.com/watch?v=2c1L19ZP5Qg
  • https://docs.google.com/presentation/d/1DUigTm6Uh43vatHkB4rFkVVIt1zf7zB7Z5tpGTy2oFY/edit?usp=sharing

Возможно, вам также будет интересно:

  • Как посмотреть ошибки audi a6
  • Как посмотреть ошибки бмв е65
  • Как посмотреть ошибки акпп опель астра
  • Как посмотреть ошибки 500 на сайте
  • Как посмотреть отчет ошибок windows 10

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии