Android developer error message

Методы лечения различных ошибок в Android Studio при разработке проекта

Сегодня хотел бы поделиться своим анализом и способами лечением разных ошибок при разработке своего продукта в Android Studio. Лично я, не раз сталкивался с различными проблемами и ошибками при компиляции и/или тестировании мобильного приложения. Данный процесс, всегда однообразный и в 99% случаев и всегда нужно тратить n-колличество времени на его устранение. Даже, когда ты уже сталкивался с данной проблемой, ты все равно идешь в поисковик и вспоминаешь, как же решить ту или иную ситуацию.

Я для себя завел файлик, в котором отметил самые частые ошибки — потратив на это несколько часов и перечислил самые популярные ошибки (в дальнейшем планирую просто их запомнить), чтоб сократить свое время в дальнейшем.

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

1) Если подчеркивает красным код, где используются ресурсы: R. — попробовать (но вероятно не поможет): Build -> Clean Project.

В принципе на Build -> Clean Project можно не терять времени, а лучше всего — слева переключиться на Project, открыть каталог .idea, затем каталог libraries и из него удалить все содержимое. Затем нажать кнопку Sync Project. А затем (если все еще красное, но скорее всего уже будет все ок ) Build -> Clean Project.

2) После внезапного выключения компьютера, после перезапуска может быть во всех проектах весь код красным. Перед этим может быть ошибка: Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of ‘adb version’. Есть три решения — первое помогло, второе нет (но может быть для другого случая), а третье — не пробовал:

а) File — Invalidate Caches/Restart — Invalidate and Restart

б) Закрыть студию. В корне папки проекта удалить файл(ы) .iml и папку .idea. Вновь запустить студию и импортировать проект.

в) Нажать Ctrl-Alt-O и запустить оптимизацию импорта.

Кстати, adb сервер можно проверить на версию (и работоспособность) и затем перезапустить:

3) Если Android Studio выдает приблизительно такую ошибку: Error:Execution failed for task ‘:app:dexDebug’.

Надо слева переключиться на опцию Project, найти и удалить папку build которая лежит в папке app, т.е. по пути app/build. Затем перестроить весь проект заново: Build -> Rebuild Project.

Такое же решение если ошибка типа: «не могу удалить (создать) папку или файл» и указан путь, который в ведет в app/build. Тоже удаляем папку build и ребилдим проект.

4) В сообщении об ошибке упоминается heap — виртуальная память. А ошибка обычно вызвана ее нехваткой, т.е. невозможностью получить запрашиваемый объем. Поэтому этот запрашиваемый объем надо уменьшить, т.е. переписать дефолтное значение (обычно 2048 MB которое можно изменить в настройках), на меньшее 1024 MB.

В файле проекта gradle.properties пишем:

5) Android Studio пришет примерно такую ошибку: Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to «83648b99316049d63656d7276cb19cc7e95d70a5»

Возможные причины (кроме необходимости регулярного обновления SDK):

а) Загруженный проект был скомпилирован с помощью уже несовместимого старого gradle плагина. В этом случае надо найти и подключить в своем build.gradle проекта этот более старый плагин. т.е. попробовать более старые версии, например: 1.1.3 (часто именно 1.1.x и подходит).

Найти все версии можно здесь.

б) Если в build.gradle проекта используется beta-версия плагина — это означает, что срок ее истек. Посмотреть последние релизы (продакшн и бета) можно также здесь:

6) Иногда при подключении сторонних библиотек могут дублироваться некоторые файлы (обычно связанные с лицензированием). В сообщении будет что-то содержащее слова: duplicate files. Решение — надо посмотреть в сообщении об ошибке или в документации подключенной сторонней библиотеки — какие именно файлы стали избыточными, и перечислить их в build.gradle модуля для исключения (exclude) из билда.

Это делается в директиве packagingOptions (которая, в свою очередь, находится в директиве android).

Источник

Android in-app purchases, часть 4: коды ошибок от Billing Library и как не облажаться с тестированием

Привет, я Влад, core разработчик Adapty SDK для Android. Продолжаю серию статей про то, как внедрять внутренние покупки в приложение Google Play. Остальные посты можно найти по ссылкам:

Android in-app purchases, часть 4: коды ошибок от Billing Library и как не облажаться с тестированием. — Вы тут.

Сегодня мы поговорим о кодах ошибок, которые мы можем получить от Billing Library в методе getResponseCode().

Пример того, как мы передавали ошибки в свои колбэки, можно посмотреть в этой статье. С одной ошибкой мы уже знакомы по предыдущим статьям — это USER_CANCELED, когда пользователь закрывает диалог покупки, ничего не купив. Давайте познакомимся с остальными.

Коды ошибок

Начнем с самых простых ошибок – с говорящим названием ERROR (responseCode 6) и чуть более говорящим названием DEVELOPER_ERROR (responseCode 5). Для первого случая гугл пишет в документации «Fatal error during the API action», для второго – «Invalid arguments provided to the API». Например, я смог получить DEVELOPER_ERROR, когда для запроса querySkuDetailsAsync() в билдер в setType() передал пустую строку.

Но не всё так просто. Я пошел дальше и в методе launchBillingFlow() использовал измененный SkuDetails (вытащил json из SkuDetails реального продукта, поменял в нем productId и передал в конструктор новому SkuDetails). По сути это invalid argument, и я ожидал получить DEVELOPER_ERROR, но… получил ERROR.

Отдельного упоминания заслуживает текст, который показывается в диалоге в этом кейсе — сравните английский и русский вариант:

Это, конечно, был искусственный пример. Гораздо ближе к реальности кейс, когда гугл отклонил оплату. Если при тестировании покупок с тестовой карты, о чем мы расскажем в конце статьи, в диалоге покупки выбрать «test card, always declined», вернется также ошибка ERROR, но уже с адекватным текстом.

В третьей статье, где описывалась смена подписки, мы для одного из proration mode увеличили цену годовой подписки почти в 3 раза, но не сказали, какая там должна была быть ошибка, если бы мы этого не сделали. Исправляемся.

Так как там, получается, указан неправильный proration mode, по логике мы должны получить всё ту же DEVELOPER_ERROR. Но нет, мы получаем SERVICE_UNAVAILABLE (responseCode 2). Ее же мы получаем и если указать любое левое число в качестве proration mode (это int, а не enum, нас никто не остановит), и если указать неправильный purchaseToken. Смотрим в документацию про SERVICE_UNAVAILABLE – «Network connection is down». Так, стоп…

При этом еще мы видим интересный диалог.

Что еще любопытно – в кейсе с ERROR при закрытии диалога НЕ через кнопку «ОК» (то есть, теми способами, которые интерпретируются как возврат назад) в onPurchasesUpdated() пришло, собственно, ERROR, а в случае с SERVICE_UNAVAILABLE в аналогичном кейсе приходит USER_CANCELED (но если нажать «ОК» в диалоге, то мы, как и ожидали, получим SERVICE_UNAVAILABLE).

Ну и в случае с отсутствием интернета SERVICE_UNAVAILABLE тоже приходит, тут не соврали.

Вот остальные коды ошибок с небольшими комментариями, так сказать, honorable mentions.

BILLING_UNAVAILABLE (responseCode 3). Гугл поясняет, что «Billing API version is not supported for the type requested». Я смог воспроизвести эту ошибку, разлогинившись из Google-аккаунта, а также на Хуавее без Google Play Services. Возможно, она также воспроизведется на старых телефонах, где не обновляли Google Play.

SERVICE_DISCONNECTED (responseCode -1). Приложение иногда дисконнектится от сервиса Google Play. Это может произойти, если Play Store вдруг решит обновиться. Поэтому лучше перестраховаться и коннектиться перед каждым вызовом методов Billing Library, как в предыдущих статьях. А еще мы с гуглом советуем добавить какую-нибудь retry policy, если эта ошибка всё же придет в ответе.

SERVICE_TIMEOUT (responseCode -3). Название говорит само за себя — мы слишком долго ждали ответ от Google Play.

FEATURE NOT SUPPORTED (responseCode -2). В классе BillingClient есть пять констант FeatureType. Их доступность на данном устройстве можно проверять с помощью метода billingClient.isFeatureSupported(BillingClient.FeatureType.НужнаяФича). У меня на телефоне (Xiaomi Mi A2 Lite) FEATURE_NOT_SUPPORTED вернулось только для SUBSCRIPTIONS_ON_VR. При этом для IN_APP_ITEMS_ON_VR, как и для всех остальных фич, вернулось OK.

ITEM_NOT_OWNED (responseCode 8). Возникает при попытке законсьюмить покупку, которой у нас нет. Например, повторно после успешного консьюма.

ITEM_ALREADY_OWNED (responseCode 7). А тут наоборот – при попытке купить продукт, который у нас уже есть. В таком кейсе просто нужно обновить UI и сделать кнопку покупки некликабельной.

Самая популярная ошибка

Последняя и, наверное, самая популярная ошибка в начале пути внедрения in-app purchases — это ITEM_UNAVAILABLE (responseCode 4). Она говорит о том, что продукт недоступен для покупки, но не говорит, почему. А причины могут быть самые разные: от тестирования на неправильном аккаунте или неправильной сборке до покупки неактивированного продукта.

Читайте также:  Touch problem in android

Вот чек-лист, что нужно сделать, чтобы избежать ее при тестировании:

Отправить в ваш test track сборку с Billing Library. Это обязательное условие — при этом вы можете тестировать и на дебажных сборках с таким же applicationId, но важно, чтобы хотя бы один раз сборка с Billing Library была загружена в Play Console.

Добавить в этот test track гугл-аккаунты тестировщиков, что особенно актуально для internal testing или закрытой альфы/беты. Там же будет ссылка в разделе How testers join your test, по которой тестировщики должны будут принять приглашение.

Покупать можно только активированный продукт. После создания продукта в Play Console есть кнопка activate, более детально процесс создания продукта мы описывали в первой статье.

Удостовериться, что тестирование на устройстве проходит с гугл-аккаунта, который является тестировщиком. Очевидный пункт, но бывает всякое, и это тоже нужно проверить, если вы получили такую ошибку.

applicationId сборки, с которой тестируется покупка, должно полностью совпадать с applicationId из Play Console. Это особенно важно для тех, у кого добавляется суффикс в дебажных сборках.

Добавить email-адреса тестировщиков в раздел Setup → License Testing в левом меню аккаунта (не приложения), чтобы они покупали продукты бесплатно с тестовой карты, а не с реальной. Еще один плюс, что подписки в данном случае будут иметь тестовую длительность. Не связано с этой ошибкой, но тоже полезное знание.

Заключение

Ошибки способны сильно усложнить работу, поэтому всегда важно понимать, как они могут возникнуть. Учитывая, сколько шагов нужно пройти, чтобы получить доступ к продуктам, проще всего словить ITEM_UNAVAILABLE. Поэтому я надеюсь, что мой чек-лист вам поможет.

Про Adapty

Для более простой работы с ошибками советую попробовать Adapty SDK для внедрения внутренних покупок в приложения. Кроме технической части, Adapty даёт много преимуществ:

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

Когортный анализ отвечает на вопрос, как быстро сходится экономика.

А/Б тесты увеличивают выручку приложения.

Интеграции с внешними системами позволяют отправлять транзакции в сервисы атрибуции и продуктовой аналитики.

Промо-кампании уменьшают отток аудитории.

Open source SDK позволяет интегрировать подписки в приложение за несколько часов.

Серверная валидация и API для работы с другими платформами.

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

Источник

How to Solve Android’s 13 Most Common Error Messages

Testing is a crucial part of Android development, allowing you to iron out all the bugs, errors and performance problems that may be lurking in your app, before you unleash it on the general public.

Every time you encounter an error, Android generates an error message, and then either displays that message as part of Android Studio’s Logcat Monitor or as a dialogue on the device you’re using to test your app.

These error messages are typically short and to the point, and at first glance may not seem all that helpful. However, these messages actually contain all the information you need to get your project back on track—you just need to know how to decipher them!

In this article, we’re going to take an in-depth look at the 13 error messages you’re most likely to encounter when developing any Android app. We’ll be scrutinising what each of these error messages really means, examining all the possible reasons why you might encounter each error and, most importantly, sharing step-by-step instructions on how you can resolve them.

Spotting Error Messages

There’s a wide range of error messages you may encounter when testing your app, ranging from severe errors that will cause your app to crash the very first time you try to install it on a target device to more subtle errors that degrade your application’s performance over time.

Depending on the kind of error you encounter, Android will display the error message either on the device you’re using to test your app or in Android Studio.

Spotting error messages that appear on a physical device or AVD is easy—you just need to be paying attention to any dialogues that appear on your device’s screen! However, spotting errors that appear in Android Studio can be tricky, as the Logcat Monitor records a huge amount of information, making it easy to miss important error messages.

The easiest way to make sure you don’t miss out any error messages is to open Logcat Monitor’s Verbose dropdown and set it to Error, which will filter out everything except error messages.

1. R.layout.main Cannot Be Found / Cannot Resolve Symbol R

This error is caused when Android Studio can’t generate your R.java file correctly, and it can often crop up out of nowhere—one minute everything will be working fine, and the next minute every part of your project is failing to compile. To make matters worse, when Android Studio encounters the R.layout error, it’ll usually flag all your layout resource files as containing errors, which makes it difficult to know where to start looking for the source of the error.

Often, the most effective solution is the simplest: clean and rebuild your project. Select Build > Clean Project from the Android Studio toolbar, wait a few moments, and then build your project by selecting Build > Rebuild Project.

If a single clean/rebuild cycle doesn’t work, then try repeating this process a few times, as some developers have reported positive results after completing multiple clean/rebuild cycles in quick succession.

If you encounter this error after moving some files and directories around, then it’s possible that the R.layout error is being caused by a mismatch between Android Studio’s cache and your project’s current layout. If you suspect this may be the case, then select File > Invalidate Caches / Restart > Invalidate and Restart from Android Studio’s toolbar.

Issues with the names of your resources can also prevent the R.java file from being created correctly, so check that you don’t have multiple resources with the same name and that none of your file names contain invalid characters. Android Studio only supports lowercase a-z, 0-9, full stops and underscores, and a single invalid character can cause an R.layout error across your entire project, even if you don’t actually use this resource anywhere in your project!

If you do identify and resolve an error, but Android Studio is still displaying the R.layout error, then you may need to complete a clean/rebuild cycle before Android Studio properly registers your changes.

2. Too Many Field References….Max is 65,536

When you compile your app, the APK contains executable bytecode files in the form of Dalvik Executable (DEX) bytecode files. The DEX specification states that a single DEX file can reference a maximum of 65,536 methods, and if you encounter the Too many fields… error then it means your app has gone over this limit. Note that this is a limitation on the number of methods your project references, and not the number of methods your project defines.

If you encounter this error, then you can either:

  • Reduce the number of references in your project. One of the most effective ways of trimming your method references is to review your application’s dependencies, as these are often one of the biggest contributors of method references.
  • Configure your app to use more than one DEX file, by enabling multidex.

The process of enabling multidex support will vary depending on the versions of Android your project supports.

If you’re targeting Android 5.0 or higher, then the first step is opening your module-level build.gradle file and setting multiDexEnabled to true :

However, if your minSdkVersion is 20 or lower, then you’ll need to add the multiDexEnabled true attribute and then add the multidex support library as a project dependency:

The next step depends on whether or not you’re overriding the Application class.

If your project does override the Application class, then open your Manifest and add the following to the tag:

If your project doesn’t override the Application class, then you’ll need to extend MultiDexApplication instead:

Finally, if you do override the Application class but can’t change the base class, then you can enable multidex by overriding the attachBaseContext() method and calling MultiDex.install(this) , for example:

3. Please Choose a Valid JDK Directory

If you’re getting a JDK error whenever you try to build your app, then it means Android Studio is struggling to find where the JDK is installed on your development machine.

To fix this error:

  • Select File > Project structure… from the Android Studio toolbar.
  • Select SDK Location from the left-hand menu.
  • Make sure the Use embedded JDK checkbox is selected.

If this doesn’t solve the problem, then navigate back to File > Project structure… > SDK Location, and manually enter the full file path for your JDK. If you’re not sure where the JDK is installed on your development machine, then you can find out by opening the Terminal (Mac) or Command Prompt (Windows) and entering the following command:

Читайте также:  Android делаем свою кнопку

4. Error Installing APK

While AVDs are great for testing your app across a wide range of different hardware and software, you should always test your app on at least one physical Android smartphone or tablet. However, Android Studio’s ability to recognize a connected Android device is notoriously hit and miss.

If you’ve attached your device to your development machine but are encountering an Error installing APK message whenever you try to install your APK, or your device isn’t even appearing in the Select Deployment Target window, then try the following fixes:

Check USB debugging is enabled.

Open your device’s Settings, then select Developer Options, and make sure USB Debugging is enabled. If you don’t see Developer Options in the Settings menu, then select About Phone and keep tapping Build Number until a You are now a developer notification appears. Return to the main Settings screen, and you should find that Developer Options has been added.

Check your smartphone or tablet’s screen.

Sometimes your device may require some additional input before it connects to your development machine. For example, it may be asking you to choose between different modes, or to explicitly authorize the connection.

Make sure you have the correct USB driver installed.

If you’re developing on Windows, then you’ll need to download the appropriate OEM USB driver for your device. If you’re a Nexus user, then you can download the Google USB driver through Android Studio’s SDK Manager.

Check that your device meets your project’s minimum SDK requirements.

You’ll find your project’s minimum SDK in your module-level gradle.build file, and can check what version of Android is installed on your device by opening its Settings and swiping to the About Phone section.

Try restarting your adb (Android Debug Bridge) process.

Open a Terminal or Command Prompt window, and then change directory ( cd ), so it’s pointing at your platform-tools window, for example:

Then, terminate and restart the adb process by entering the following commands, one after the other:

Restart everything!

If all else fails, then try disconnecting and then reconnecting your device, restarting your device, restarting Android Studio and, as an absolute last resort, restarting your development machine.

5. INSTALL_FAILED_INSUFFICIENT_STORAGE

If you encounter this error when attempting to install your project, then it means the target device doesn’t have enough memory.

If you’re trying to install your project on an AVD, then you should check how much space you’ve assigned this particular AVD:

  • Launch the AVD Manager.
  • Find the AVD in question, and click its accompanying Edit this AVD icon.
  • In the window that appears, click Show Advanced Settings.
  • Scroll to the Memory and Storage section.

This section lists the various types of memory you’ve allocated to this particular AVD. If any of these values are unusually low, then you should increase them to more closely reflect the memory that’s available to your typical Android smartphone or tablet:

  • RAM. The amount of RAM available to the emulated device.
  • VM Heap. How much heap space (i.e. memory) is allocated to the Virtual Machine (VM) of the emulated smartphone or tablet.
  • Internal Storage. The amount of non-removable memory available to the emulated device.
  • SD card. The amount of removable memory available. If you want to use a virtual SD card that’s managed by Android Studio, then select Studio-managed and enter the size of the virtual SD card you want to create (the minimum recommended value is 100 MB). Alternatively, you can manage the SD card “space” in a file, by selecting External file and then specifying the location you want to use.

If there’s nothing odd about your AVD’s memory, or you’re trying to install your app on a physical Android smartphone or tablet, then this error usually means that your compiled app is simply too large. An application that takes a significant bite out of the device’s memory at install time is never going to go down well.

If you need to dramatically reduce the size of your APK, then try the following techniques:

Use ProGuard to remove unused classes, fields, methods, and attributes. To enable ProGuard, open your module-level build.gradle file and add the following:

Optimize your libraries. Try to remove any unnecessary or memory-intensive libraries from your project. If you do need to use a large library, then check whether there’s any way you can optimize this library for the mobile environment, as external library code often isn’t written with mobile in mind. You should also bear in mind that many libraries contain a large amount of localized strings. If your app doesn’t officially support these libraries, then you may be able to reduce the size of the library by telling Gradle not to include these strings in your compiled APK. To specify the languages that your app officially supports, open your module-level build.gradle file and use the resConfigs attribute. For example, here we’re specifying that we want to include only English-language strings in our project:

Consider whether your APK contains a large amount of content that the individual user may download but never use. For example, a device with an hdpi screen doesn’t have much use for xxxhdpi assets! One of the most effective ways of reducing the size of your APK is to separate it into multiple APKs, so when the user downloads your app, they’ll receive an APK that contains only the code and resources that make sense for their particular device. You’ll find more information on creating APKs that target different screen densities and specific ABIs (application binary interfaces) over at the official Android docs.

6. ActivityNotFoundException

An ActivityNotFoundException occurs when a call to startActivity(Intent) or one of its variants fails because the Activity can’t execute the given Intent .

The most common cause of an ActivityNotFoundException is forgetting to declare an activity in your manifest, so open your manifest and check that you’ve declared all your activities. You should also check that you’ve declared each activity correctly, using either a fully qualified class name or a full stop as a shorthand for the package name. For example, both of the following are valid:

If you can’t spot any problems with your manifest, then there are a few other potential causes of ActivityNotFoundExceptions . Firstly, if you encounter this error after moving an Activity class from one package to another, then it’s possible that you’ve confused Android Studio and just need to clean and rebuild your project.

An ActivityNotFoundException can also be caused if an error in the target Activity is not loading correctly. To check whether this is occurring in your project, put your intent code inside a try-catch block:

Run your application again, and then take a look at Android Studio’s Logcat Monitor to see whether it’s captured any exceptions that may be preventing the target activity from being created. If this is the case, then resolving these errors should solve the ActivityNotFoundException , too.

7. ClassCastException

The ClassCastException error is related to Java’s type conversion feature, which allows you to cast variables of one type to another. You encounter a ClassCastException when you try to cast an object to a class of which it’s not an instance. For example, both of the following code snippets will result in a ClassCastException :

This error message contains information about the line that’s causing the ClassCastException error, so navigate to this part of your project, check what objects are being cast there, and resolve any mismatch.

If you can’t spot a problem with your casting, then consider whether you’ve recently moved some Views around in your layout resource files, as some users have reported encountering a ClassCastException after rearranging their Views . If you suspect this may be the cause of your ClassCastException , then tell Android Studio to regenerate your layout files from scratch, by performing a clean/rebuild cycle. This forces Android Studio to properly register your recent layout changes, which should resolve your ClassCastException .

8. NullPointerException

In Java, when you declare a reference variable, you’re actually creating a pointer to an object. You can declare that an object is currently pointing at an unknown piece of data by assigning a null value to that object’s reference. Null values can be useful in coding some design patterns, but if you encounter a NullPointerException (NPE) then it means that you’ve tried to use a reference that’s pointing at a null value, as though it were referencing an object. Since there’s no code to execute in the location where this reference is pointing, you wind up with an NPE.

An NPE is usually accompanied by information about where this exception was caught, so the Logcat Monitor should contain the exact line where this error occurred. Navigate to this area of your project and identify the reference that equals null. You’ll then need to find the location where the value should be set, and set it.

Читайте также:  Ресивер xbox 360 для андроид

The findViewById method can also return null if the requested View can’t be found, so if your NPE is occurring in a line that contains a findViewById , check that you’ve initialized the layout that contains this View . Also be on the lookout for any spelling mistakes or typos that may have crept into your findViewById call, as these can also result in an NPE.

To avoid NPEs occurring in your project, make sure all your objects are initialized before you attempt to use them, and always verify that a variable isn’t null before you request a method or field from that object.

9. Application Not Responding Error

This is an error that appears as a dialogue on the Android device or AVD you’re using to test your app. The Application Not Responding (ANR) error occurs when your app’s UI freezes and remains unresponsive to user input for more than five seconds. This usually happens because your app is trying to perform lengthy or intensive operations on Android’s main UI thread.

In Android, the main UI thread is responsible for dispatching all user input events to the appropriate UI widgets, and for updating your app’s UI. However, this thread can only process one task at a time, so if you block the main thread with any long-running or intensive operations, then your UI will be completely unresponsive until this task is complete.

If you encounter an ANR message while testing your app, then you definitely need to take a look at the work you’re performing on the main thread. However, if you don’t explicitly encounter this error but notice that your app sometimes feels sluggish or laggy, then this is an indication that you’re on the verge of an ANR error, and once again you should take a look at the state of your UI thread.

To resolve ANR errors (and near-ANR errors), you need to identify all the operations that have the potential to run slowly, or that require significant processing power, and then move them off the main thread. You do this by creating a worker thread where these operations can be performed with zero risk of blocking the main UI thread.

There are several methods of creating additional threads, but the simplest solution is to use an AsynTask , as this class already contains its own worker thread and an onPostExecute() callback that you can use to communicate with Android’s main UI thread.

However, AsyncTasks are better suited to performing short background operations, so if you need to perform a long-running operation, then you should use a Service or an IntentService instead.

Although moving long-running and intensive tasks off the main thread will have the most impact on your app’s performance, it’s best practice to perform as little work as possible on the main UI thread. Even running a small amount of unnecessary code on the main thread can have an impact on your app’s responsiveness, so once you’ve successfully relocated all of your long-running and intensive operations, you should look at whether there’s any more code that you can move off the main thread.

10. Only the Original Thread That Created a View Hierarchy Can Touch Its Views

In Android, you can update your UI from the main thread only. If you try to access UI elements from any other thread, then you’re going to encounter this error.

To resolve this issue, identify the part of your background task that’s attempting to update the UI and move it to a runOnUiThread , for example:

Alternatively, you can use a handler or perform your background work in an AsyncTask, as you can communicate with the main thread using AsyncTask’s onPostExecute() callback method. Finally, if you find yourself regularly switching between threads, then you may want to look into RxAndroid, as this library allows you to create a new thread, schedule work to be performed on this thread, and then post the results to the main thread, all with just a few lines of code.

11. NetworkOnMainThreadException

This exception is thrown when your app attempts to perform networking operations on the main thread, such as sending API requests, connecting to a remote database, or downloading a file. Since network operations can be time-consuming and labour-intensive, they are highly likely to block the main thread, so Android 3.0 (Honeycomb) and higher will throw this error whenever you attempt to make a network request on the main thread.

If you do encounter a NetworkOnMainThreadException , then find the networking code that’s running on your main thread, and move it to a separate thread.

If you do need to make frequent networking requests, then you may want to take a look at Volley, an HTTP library that initiates its own background threads so that all networking requests are performed off the main thread by default.

12. Activity Has Leaked Window That Was Originally Added Here

This error occurs when trying to show a dialogue after exiting the Activity. If you do encounter this issue, then open your Activity and make sure you’re dismissing the dialogue properly, by calling dismiss() in either your Activity’s onDestroy() or onPause() method, for example:

13. OutofMemoryError

This error occurs when your app makes a memory request that the system can’t meet. If you encounter this error message, then start by ruling out all of the most common memory management mistakes. Check that you’ve remembered to unregister all your broadcast receivers and that you’ve stopped all of your services; make sure you’re not holding onto references in any static member variables, and that you’re not attempting to load any large bitmaps.

If you’ve ruled out all the obvious causes of an OutOfMemoryError , then you’ll need to dig deeper and examine exactly how your app is allocating memory, as chances are there are a few areas where you can improve your app’s memory management.

Android Studio has a whole area dedicated to helping you analyze your app’s memory usage, so start by selecting View > Tools Window from the Android Studio toolbar. At this point you’ll see either an Android Monitor or Android Profiler option, depending on the version of Android Studio you have installed.

We’ve discussed working with the Memory Monitor on this website before, but since Android Profiler is a new addition to Android Studio, let’s take a quick look at its major features.

When you open Android Profiler, it starts recording three pieces of information automatically.

Since we’re interested in the way our app is using memory, give the Memory section a click, which will launch the Memory Profiler.

The Memory Profiler consists of a timeline that displays the different kinds of memory currently being allocated by your app, for example Java, native, and stack. Above this graph you’ll find a row of icons that you can use to trigger different actions:

  • Force a garbage collection event.
  • Take an Hprof snapshot of the application memory. This is a snapshot of all the objects in your app’s heap, including the kind of objects your app is allocating, the number of allocated objects, and how much space these objects are taking up.
  • Record memory allocations. By recording your app’s memory allocations while performing certain actions, you can identify the specific operations that are consuming too much memory.

To identify the parts of your application that are responsible for the OutOfMemoryError , spend some time interacting with your app, and monitor how your app’s memory allocations change in response to different actions. Once you’ve identified the section of your project that’s causing the problem, spend some time scrutinising it for any memory leaks, as well as any inefficiencies in the way it’s using memory.

Conclusion

In this article we looked at 13 of the error messages you’re most likely to encounter when developing for Android. We discussed all the different factors that can contribute towards these errors, and the steps you need to take to resolve them.

If you’re being plagued by an error message that we didn’t cover, then your first step should be copy/pasting the entire error message into Google, as this will often turn up threads and blog posts where people are discussing how to solve this particular error.

And, if you can’t find a solution anywhere on the web, then you can always reach out to the Android community for help directly, by posting your question to Stack Overflow.

While you’re here, check out some of our other posts on Android app development!

Источник

Оцените статью