Android studio в приложении произошла ошибка

Я разрабатываю приложение, которое использует AppCompatActivity. На api 21+ все нормално работаеть а не запускается приложение на api 19 или меньше с сообщением проложение остановлено. Хочу чтобы на api меньше 19 исползовалься материальный дизайн.

Файл activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="tj.rs.materialdesignexample.MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"/>

        <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>
    </RelativeLayout>

Файл gradle.build

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "28.0.1"
    defaultConfig {
        applicationId "tj.rs.materialdesignexample"
        minSdkVersion 17
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:22.2.1'
    testCompile 'junit:junit:4.12'
}

Файл MainActivity.java

package tj.rs.materialdesignexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Привет, помогите срочно пожалуйста я написал первое приложение, в android studio нет ошибок. APK в смартфоне устанавливается, НО не запускается, пишет ошибку эту:
5e9f5fec30252151397425.jpeg

Уже 1 месяц не могу найти проблему, все пробовал.
Приложение работает с Firebase Auth, Firestore
Вот ниже ссылка файла Скриптов проекта

https://drive.google.com/file/d/1n15wPIvSuES_kJ2zJ…

Заранее спасибо!


  • Вопрос задан

    более трёх лет назад

  • 2947 просмотров

Пригласить эксперта

Нуу… а вы пробовали произвести логирование и дебаг?
Что выдает logcat? Пробовали ли вы в Android Studio добавить Exception Breakpoint и поймать исключение.
Просто, скриншота, где написано что в приложении есть ошибка недостаточно.
Также попробуйте воспроизвести ошибку на различных версиях Android и т.д.

Было бы очень здорово, если бы вы конкретно описали, что именно ВСЁ вы пробовали.
Конкретно в вашем случае надо пробовать смотреть logcat, это в Android Studio, когда вы запускаете приложение на подключенном телефоне или эмуляторе.
Вот вам видео урок про logcat
https://www.youtube.com/watch?v=cCmkOQcOex4

P.S. я не поленился заглянгуть в ваш код, и там не вооруженным глазом видно, что у вас в postButton получается null (потому что findViewById(R.id.post_button) не найдет эту кнопку в layout.activity_main)
А потом вы на postButton пытаетесь повесить обработчик.
Но я уверен, это не единственная ошибка, научитесь использовать logcat.

Смогли разобраться? Если да то напишите пожалуйста как.
В комментах много воды


  • Показать ещё
    Загружается…

08 июн. 2023, в 22:08

50000 руб./за проект

08 июн. 2023, в 22:01

3000 руб./за проект

08 июн. 2023, в 21:41

5000 руб./за проект

Минуточку внимания

While developing applications in Android Studio we might encounter many errors while writing code in the editor. We know that there’s an error since the editor automatically detects in real-time and highlights it in red color like this

Well, in the above image we can see that the error occurs due to a closing bracket after orderLists in Line 58. We can say that because the editor detects that in real-time and warns us with red underlining at that line. Now we can write error-less code and our app should run, right? Well, NO. Because the editor only helps in detecting the syntax error in the code. Whereas we have many other kinds of errors that might cause our app not to work the way we want it to be. Runtime and Logical errors are the common ones and cannot be detected in the editor. 

Now the question is – We have written 100’s and 1000’s lines of error less codes or I should syntax error free code that compiles and runs without any problem. But my app still stops working or some features don’t work the way I want it to?

In this situation, the Logcat acts as our best friend. Logcat Window is the place where various messages can be printed when an application runs. Suppose, you are running your application and the program crashes, unfortunately. Then, Logcat Window is going to help you to debug the output by collecting and viewing all the messages that your emulator throws. So, this is a very useful component for the app development because this Logcat dumps a lot of system messages and these messages are actually thrown by the emulator. In Android Studio one of the most used tools is Logcat. Logcat window in Android Studio is used to display real-time system messages and messages that are added in the Log class of the app. To open Logcat Click View > Tool Windows > Logcat (Alt + 6 or from the toolbar window).

Most Common Types of Error

  • NullPointerException – When expecting from null variables, objects, or classes.
  • IOException – Exceptions produced by failed or interrupted I/O operations.
  • OutOfMemoryError – When an object cannot be allocated more memory by its garbage collector.

Solutions to fix App Crash 

1. Observe the App Crash

Suppose you have built an application with multiple activities or fragments or both then you need to observe and see which action causes the application to crash. This might sometimes help you automatically remember or recall what mistake was made and which part of the app is causing that.

2. Find the Stack Trace 

It is best to look at the logcat to find the exact point of error. You can open the logcat and in the error section start reading the log error messages. Scroll to the bottom of the screen and look for the line that says Caused by. You may find the file name and line number in the logcat messages, which will lead you directly to the cause of the error. Look for elements to resolve the error. 

  • File Name
  • Line Number
  • Exception Type
  • Exception Message

3. Investigation Techniques

There are times when you might not find the exact line of code or file name that’s causing the error. So you should following techniques to investigate by yourself – 

  • Toast – Toast messages are used to display alerts messages and in this case, you can use them to display failure messages.
  • Logging – Logging is used to print messages in the logcat.
  • Breakpoints – It can be used to investigate values at the points where breaks are applied.

4. Google for Solution

There will be times we cannot fix the bug by ourselves and that’s ok. That’s the time you should start searching for solutions on the internet. Try googling with the main query message like – java.lang.NullPointerException. Generally, try looking for links of StackOverflow with maximum matching keywords of your search in the google search results. Afterward, you can go for other portals if you do not find the solution in StackOverflow.

Last Updated :
30 Jun, 2021

Like Article

Save Article

Кротяка

7 / 7 / 1

Регистрация: 20.12.2010

Сообщений: 392

1

01.03.2016, 04:56. Показов 2667. Ответов 12

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте. По непонятным причинам слетел Eclipse, при этом в буквальном смысле слова «почистив» все xml документы в моих проектах, тем самым наполовину их уничтожив. Но я не об этом хотел спросить. После переустановки всех компонентов, нужных для работы, во первых, я получил следующую проблему:

XML
1
2
3
4
5
6
7
8
9
10
NOTE: This project contains Java compilation errors, which can cause rendering failures for custom views. Fix compilation problems first.
 
Failed to find the style corresponding to the id 2130772027
Failed to find the style corresponding to the id 2130771996
java.lang.NullPointerException
Failed to load AppCompat ActionBar with unknown error.
Exception details are logged in Window > Show View > Error Log
The following classes could not be instantiated:
- android.support.v7.app.WindowDecorActionBar (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.

Ну. т.е. при создании xml-файла и собственно активити это самое активити толком и не создавалось, сетуя на отсутствие одного из графических элементов. Погуглив, благо, я сумел справится с этой проблемой, сменив тему оформления на графической панели.
Но появилась проблема гораздо хуже: теперь даже при запуске приложения «Hello World!» (Обращаю внимание на то, что кода моего в программе нет, есть только дефолтный, который добавляет компилятор при создании проекта) приложение крешится со стандартным сообщением «В приложении … произошла ошибка»…Хотя в проекте ошибок нет, ни в коде программы, ни теперь уже в активити или других xml-файлах…
Раньше кодил и всё было нормально, подобного не было ни разу, теперь вот столкнулся с такой проблемой… сутки пытался решить сам — толку ноль…облазил форумы, читал хелп…
Может быть кто то может помочь в решении этой проблемы? Ну или подсказать хотя бы, в какую сторону смотреть для устранения сего недуга? Буду очень благодарен за помощь.



0



59 / 48 / 13

Регистрация: 03.09.2013

Сообщений: 474

01.03.2016, 10:40

2

Оффтоп, ну какой эклипс, зачем он вам вообще?



0



7 / 7 / 1

Регистрация: 20.12.2010

Сообщений: 392

01.03.2016, 12:34

 [ТС]

3

DemD10, ну я ведь не в Visual Studio пытаюсь программировать) всё таки Eclipse поддерживает разработку Android-приложений, следовательно, должен работать нормально. К тому же, я уже привык к этой среде, так уж получилось, что мне посоветовали именно её, а не Android Studio, когда я начинал кодить под Android.



0



2882 / 2294 / 769

Регистрация: 12.05.2014

Сообщений: 7,978

01.03.2016, 12:38

4

переходи на андроид студио, не мучай себе и другим голову
гугл больше не поддерживает эклипс



0



59 / 48 / 13

Регистрация: 03.09.2013

Сообщений: 474

01.03.2016, 14:13

5

Ну так почти все начинали с Eclipse. Но тебе 99% человек скажут что переход происходит безболезненно, 2-3 дня и тебе уже не нужен никакой Eclipse.



0



Android

245 / 242 / 52

Регистрация: 19.01.2013

Сообщений: 1,896

Записей в блоге: 3

01.03.2016, 17:04

6

Цитата
Сообщение от DemD10
Посмотреть сообщение

Но тебе 99% человек скажут что переход происходит безболезненно, 2-3 дня и тебе уже не нужен никакой Eclipse.

Все точно так!)



0



344 / 236 / 33

Регистрация: 16.01.2010

Сообщений: 747

01.03.2016, 22:37

7

Цитата
Сообщение от Кротяка
Посмотреть сообщение

Может быть кто то может помочь в решении этой проблемы? Ну или подсказать хотя бы, в какую сторону смотреть для устранения сего недуга? Буду очень благодарен за помощь.

Библиотеки подгрузили? (android support library) это в SDK manager.

Не по теме:

P.S Мне студия не нравиться, работает медленнее, это гардел вообще морозит. Каждый раз, запускаю эта сволочь чего — нибудь, да придумает нового. Что бы не запускаться. Эклипс такого не вытворял.
И это уже не считая того, что все проекты что импортировал, так и не смог русифицировать — все комментарии превратились в ромбические вопросы, и никакая кодировка, никакие танцы с бубнами не помогли, только ручками переписать.



0



59 / 48 / 13

Регистрация: 03.09.2013

Сообщений: 474

02.03.2016, 07:49

8

Ой всё, холивар со староверами бесполезен. Вы и веник наверно вместо пылесоса используете, находя причины почему он плох.



0



7 / 7 / 1

Регистрация: 20.12.2010

Сообщений: 392

02.03.2016, 14:09

 [ТС]

9

Vladimirys, библиотеку подгрузил конечно, но это не помогает…



0



91 / 86 / 12

Регистрация: 08.08.2013

Сообщений: 667

02.03.2016, 14:42

10

Я тоже очень не хотел на студию переходить.
Очень тормозило, докупил к 4 гб еще 8 оперативы, всё стало грузить менее минуты.
Но это не главное.
Открыл студию, создался hello world, я ничего не менял, ничего не трогал просто загрузил в телефон, при открытии приложения в телефоне оно вылетает.
Некоторые сэмплы загруженные из из гугла были с ошибками и компилироваться даже не хотели, некоторые компилировались но вылетали.
Со всеми проблемами разобрался, теперь работаю только в студии, она удобнее и лучше, но на переход и решение проблем я убил не один день.
Так что считаю просто везунчиками тут тех, кто пишет про 2-3 дня, не более, ведь на 99% уверен что мало кто слышал до студии о gradle.



1



7 / 7 / 1

Регистрация: 20.12.2010

Сообщений: 392

02.03.2016, 16:11

 [ТС]

11

_Night_Scream_, и всё же, не до конца вас понял…что конкретно мне нужно предпринять для того, чтобы исчезли эти вылеты при запуске приложения? (кроме установки студии, это, в общем то, ясно и так, и судя по вашему ответу, студия проблему не решает…)



0



91 / 86 / 12

Регистрация: 08.08.2013

Сообщений: 667

02.03.2016, 16:23

12

Кротяка, я просто в дискуссию влез о ide, лично вам помочь чем не знаю, но у меня проблема была с телефоном explay, разработчики что-то намудрили что appcompat не становится, только с флагом minifyEnabled в gradle (обфускация). Попробуйте.



1



7 / 7 / 1

Регистрация: 20.12.2010

Сообщений: 392

03.03.2016, 02:54

 [ТС]

13

_Night_Scream_, собственно, я только что попробовал запустить приложение на эмуляторе — результат не изменился, следовательно, проблема не в телефоне

Добавлено через 10 часов 17 минут
Разобрался. Проблема была в классе ActionBarActivity, от которого по умолчанию наследуется новый класс в проекте и который был заблокирован разработчиками(собственно он был перечёркнут в коде). Заменил его на простой Activity и проблема решилась. При чём проблема была актуальна лишь для моего телефона(Lenovo A369i, Андрюха 4.2.2), пробовал на телефоне товарища с Android 5.1 — ошибки не было…
Правда так и не смог решить проблему темы оформления(на дефолтной ошибка, а при выборе любой другой отображается стандартная), но это мелочи.
Может кому-нибудь когда-нибудь пригодится мой горький опыт) Всем спасибо за отклик.



0



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

Понравилась статья? Поделить с друзьями:
  • Android process media произошла ошибка lenovo
  • Android process gapps произошла ошибка
  • Android process acore что это значит произошла ошибка
  • Android process acore произошла ошибка что это такое
  • Android process acore произошла ошибка как исправить на телефоне