Время на прочтение
3 мин
Количество просмотров 58K
Сегодня хотел бы поделиться своим анализом и способами лечением разных ошибок при разработке своего продукта в 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 сервер можно проверить на версию (и работоспособность) и затем перезапустить:
adb version
adb kill-server
adb start-server
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 пишем:
org.gradle.jvmargs=-Xmx1024m
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 и подходит).
com.android.tools.build:gradle:1.1.3
Найти все версии можно здесь.
б) Если в build.gradle проекта используется beta-версия плагина — это означает, что срок ее истек. Посмотреть последние релизы (продакшн и бета) можно также здесь:
6) Иногда при подключении сторонних библиотек могут дублироваться некоторые файлы (обычно связанные с лицензированием). В сообщении будет что-то содержащее слова: duplicate files. Решение — надо посмотреть в сообщении об ошибке или в документации подключенной сторонней библиотеки — какие именно файлы стали избыточными, и перечислить их в build.gradle модуля для исключения (exclude) из билда.
Это делается в директиве packagingOptions (которая, в свою очередь, находится в директиве android).
Например, при подключении библиотеки Firebase (облачный бек-енд сервис) в случае возникновения такой ошибки в build.gradle модуля (не проекта) добавляем packagingOptions в android (уже существующие там директивы оставляем) так:
android {
...
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
}
P.S.: Думаю, данная статья была полезна. Если у вас есть еще какие-то частные проблемы при работе с проектами в Android Studio, с удовольствием выслушаю их. Как по мне, 6 проблемных причин, которые я перечислил выше — это 99% всех случаев краха проекта. Конечно, если проблема не связана с вашим личным кодом.
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
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
:
1 |
android { |
2 |
defaultConfig { |
3 |
minSdkVersion 21 |
4 |
multiDexEnabled 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:
1 |
dependencies { |
2 |
compile 'com.android.support:multidex:1.0.1' |
3 |
} |
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 <application>
tag:
1 |
<application
|
2 |
android:name="android.support.multidex.MultiDexApplication" > |
3 |
... |
4 |
... |
5 |
... |
6 |
</application>
|
If your project doesn’t override the Application
class, then you’ll need to extend MultiDexApplication
instead:
1 |
public class MyApplication extends MultiDexApplication |
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:
1 |
@Override
|
2 |
protected void attachBaseContext(Context base) { |
3 |
super.attachBaseContext(base); |
4 |
MultiDex.install(this); |
5 |
}
|
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:
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:
1 |
cd /Users/Downloads/adt-bundle-mac/sdk/platform-tools
|
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:
1 |
buildTypes { |
2 |
release { |
3 |
|
4 |
//Enable ProGuard// |
5 |
|
6 |
minifyEnabled true |
7 |
|
8 |
//Since we want to reduce our APK size as much as possible, I’m using the settings from the proguard-android-optimize.txt file// |
9 |
|
10 |
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' |
11 |
|
12 |
} |
13 |
} |
14 |
|
15 |
} |
- Use the aapt tool to optimize your drawables with lossless compression, or use a program that’s designed to reduce the size of your PNG files (zopflipng, pngcrush, OptiPNG, TinyPNG, or pngquant) or the size of your JPEGs (packJPG). Alternatively, you may want to try replacing your PNG and JPEG files with images in the WebP format.
- Remember to remove all debug-related functionality from the release version of your app. Android doesn’t require this information to run, so it’s just taking up unnecessary space.
- Scour your project for any duplicate resources. Even lightweight resources like duplicate strings contribute something towards your final APK size.
- Use Lint to identify any resources that aren’t referenced anywhere in your code, and remove these resources. To run Lint, select Analyze > Inspect Code… from the Android Studio toolbar.
- Enable resource shrinking, by adding
shrinkResources true
to your project’s build.gradle file. - If you need to use variations of the same image, then use the same base image and customize it at runtime, rather than adding multiple versions of the same image to your project. For example, you can apply different colours to an image using
android:tint
andtintMode
, and you can rotate an image usingandroid:fromDegrees
,android:toDegrees
,android:pivotX
, andandroid:pivotY
. -
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:
1 |
android { |
2 |
defaultConfig { |
3 |
resConfigs "en" |
-
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:
1 |
<activity android:name=".MainActivity"> |
1 |
<activity android:name="com.jessicathornsby.myapplication.MainActivity"> |
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:
1 |
try { |
2 |
|
3 |
//Your code here//
|
4 |
|
5 |
} catch ( ActivityNotFoundException e) { |
6 |
e.printStackTrace(); |
7 |
|
8 |
}
|
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
:
1 |
Object x = new Integer(0); |
2 |
System.out.println((String)x); |
1 |
ImageView image = (ImageView)context.findViewById(R.id.button); |
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.
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:
1 |
runOnUiThread(new Runnable() { |
2 |
@Override
|
3 |
public void run() { |
4 |
|
5 |
//Update your UI//
|
6 |
|
7 |
}
|
8 |
|
9 |
});
|
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:
1 |
@Override
|
2 |
protected void onDestroy() |
3 |
{
|
4 |
super.onDestroy(); |
5 |
if(pDialogue!= null) |
6 |
pDialogue.dismiss(); |
7 |
|
8 |
}
|
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!
Did you find this post useful?
Jessica Thornsby is a technical writer based in Sheffield. She writes about Android, Eclipse, Java, and all things open source. She is the co-author of iWork: The Missing Manual, and the author of Android UI Design.
This page will compile common issues experienced with Android Studio or above as they are experienced and recorded.
Debugging
If you want to do more in-depth debugging in your code, you can setup breakpoints in your code by clicking on the left side pane and then clicking on Run
->Debug
. You can also click on the bug icon if you’ve enabled the Toolbar (View
->Enable Toolbar
):
Android Studio also provides a built-in decompiler. You can also use Navigate
->Declaration
within the IDE and set breakpoints even within classes for which you may not necessarily have the actual source code. Notice the warning message at the top and an example of a screenshot of setting a breakpoint of a class defined in a JAR file below:
If the debugger isn’t working, check the guide section below to get things running again.
Network Traffic Inspection
If you wish to inspect network traffic, see this guide on how to troubleshoot API calls. The networking library you use determines what approach you can use.
Database Inspection
Also, the Stetho project can be used to view your local SQLLite database. See this guide for more details.
LogCat
Android Studio contains a panel to receive logging messages from the emulator, known as LogCat. If you are not seeing any log messages, click on the Restart icon .
Resetting adb
If you are having issues trying to connect to the emulator or see any type of “Connection refused” errors, you may need to reset the Android Debug Bridge. You can go to Tools
->Android
->Android Device Monitor
. Click on the mobile device icon and click on the arrow facing down to find the Reset adb
option.
Virtual Device Manager
Unable to delete emulator getting “AVD is currently running in the Emulator”
Open the Tools => Android => AVD Manager
and select virtual device that you want to delete. Click on the down arrow at the end and select the [Show on Disk]
option which will open the emulator directory. Inside the [Your Device].avd
folder, locate any *.lock
files and delete them. You can now delete the emulator. See this stackoverflow post for more details.
Android Studio Issues
Android Studio is Crashing or Freezing Up
If Android Studio starts freezing up or crashing even after rebooting the IDE or your computer, your Studio has likely become corrupted. The best way to resolve this is to clear all the caches by removing all the following folders:
~/Library/Application Support/AndroidStudio
~/Library/Caches/AndroidStudio
~/Library/Logs/AndroidStudio
~/Library/Preferences/AndroidStudio
and then uninstall Android Studio and re-install the latest stable version. This should allow you to boot Android Studio again without errors.
Android Studio Design Pane isn’t loading properly
If you find yourself opening up a layout file and not seeing the design pane rendering correctly such as:
We can try the following steps to get this functioning again:
- Try changing the API version selected in the dropdown and try a few different versions
- Click the “refresh” icon at the top right of the design pane
- Select
File -> Invalidate Caches / Restart
and restart Android Studio
You may need to install the newest version of Android and select that version within the dropdown for the pane to work as expected.
Seeing Unable to execute dex: method ID
when compiling
This might also show up as Too many field references: 131000; max is 65536.
or com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
or Error:Execution failed for task ':app:dexDebug'
in the build console. This error occurs when the total number of references within a single bytecode file exceeds the 65,536 method limit. This usually means you have a substantial amount of code or are loading a large number of libraries.
If you’ve crossed this limit, this means you’ve loaded too many classes usually due to third-party libraries. Often the culprit is the Google Play Services library. Open up your app gradle file and look for this line implementation 'com.google.android.gms:play-services:X.X.X'
. Remove that line and instead include the services selectively as outlined there. For example:
dependencies {
implementation 'com.google.android.gms:play-services-maps:8.3.0'
implementation 'com.google.android.gms:play-services-location:8.3.0'
}
This can greatly reduce the number of classes loaded. If you’ve crossed the limit even with this change, we need to adjust our project to use a multidex configuration by enabling multiDexEnabled true
in your gradle configuration and updating the application to extend from android.support.multidex.MultiDexApplication
.
Seeing java.lang.OutOfMemoryError : GC overhead limit
when compiling
You are most likely exhausting the heap size especially during compilation. Try to add inside this setting in your app/build.gradle
:
android {
.
.
.
dexOptions {
javaMaxHeapSize "4g"
}
}
You can also reduce the build time too by setting incremental
to be true:
android {
dexOptions {
incremental true
javaMaxHeapSize "4g"
}
}
See this Google discussion article for more context.
Still not working? Try to increase the heap size of Android Studio.
- Quit Android Studio.
-
Create or edit a
studio.vmoptions
file.- On Mac, this file should be in
~/Library/Preferences/AndroidStudio/studio.vmoptions
. - On Windows, it should be in
%USERPROFILE%.AndroidStudiostudio[64].exe.vmoptions
.
Increase the maximum memory to 2 Gb and max heap size of 1 Gb.
-Xmx2048m -XX:MaxPermSize=1024m`
- On Mac, this file should be in
-
Start Android Studio.
Getting “No resource found that matches given name.”
If you are using multiple layout folders and decide to rename any of your ID tags in your XML files, you may get “No resource found that matches given name.” There is a current bug in how changes are detected in nested subfolders so your best option is to not use this approach until the problem is fixed. Otherwise, you will need to do a Rebuild Project
so that the entire resource files can be regenerated and the build/ directories are fully removed. Note: Clean Project
may not work.
Getting “tooling.GradleConnectionException” errors
If you see org.gradle.tooling.GradleConnectionException
errors, you may need to install a newer version of JDK (there have been reports of 1.7.0_71 having this issue). First try to restart the adb server first.
Getting “failed to find Build Tools revision x.x.x”
If you’re opening another Android Studio project and the project fails to compile, you may see “failed to find Build Tools revision x.x.x” at the bottom of the screen. Since this package is constantly being changed, it should be no surprise that other people who have installed Android Studio may have different versions. You can either click the link below to install this specific Build Tools version, or you can modify the build.gradle file to match the version you currently have installed.
Getting “com.android.dex.DexException: Multiple dex files define”
One of the issues in the new Gradle build system is that you can often get “Multiple dex files define” issues.
If a library is included twice as a dependency you will encounter this issue. Review the libs
folder for JARS and the gradle file at app/build.gradle
and see if you can identify the library dependency that has been loaded into your application twice.
If one dependency library already includes an identical set of libraries, then you may have to make changes to your Gradle configurations to avoid this conflict. This problem usually happens when there are multiple third-party libraries integrated into your code base. See Must-Have-Libraries#butterknife-and-parceler for more information.
Another error if you attempt to include a library that is a subset of another library. For instance, suppose we included the Google play-services library but thought we also needed to include it with the play-services-map library.:
dependencies {
implementation 'com.google.android.gms:play-services:6.5.+'
implementation 'com.google.android.gms:play-services-maps:6.5.+'
}
It turns out that having both is redundant and will cause errors. It is necessary in this case to remove one or the other, depending on your need to use other Google API libraries. See this overview of the multidex issue on the Android docs.
Seeing Unsupported major.minor version 52.0
on some plugins
Some Android Studio plugins do not support Java 1.6 anymore, so it’s best to confirm what version you are using. Inside Android Studio, click on About Android Studio
. You should see the JRE version listed as 1.x.x below:
If you have multiple Java versions installed, you should make sure that v1.6 is not being used. Solutions include:
- Configuring JDK 8 as your default Java SDK within Studio. See this stackoverflow post for solutions.
- Reset your Android Studio cache and set correct gradle version as shown in this post.
On OS X machines, you can remove the JDK from being noticed. You can move it the temporary directory in case other issues are created by this change.
sudo mv /System/Library/Java/JavaVirtualMachines/1.6.0.jdk /tmp
INSTALL_FAILED_OLDER_SDK error message
If your minSdkVersion
is higher than the Android version you are using (i.e. using an emulator that supports API 19 and your target version is for API 23), then you may see an error message that appears similar to the following:
You will need to either lower the minSdkVersion
or upgrade to an Android emulator or device that supports the minimum SDK version required.
Seeing java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
You have a third-party library reference defined twice. Check your app/build.gradle
for duplicate libraries (i.e. commons-io library defined for 1.3 and another one using 2.4).
Debugger Isn’t Working: Breakpoint In Thread is Not Hit
You might notice that the debugger does not always work as expected in background threads such as AsyncTask
or when using networking libraries to send network requests. The debugger breakpoints are a little bit finicky when configured to stop outside the main thread.
In order for some of these breakpoints in the callbacks to work, you have to set them after the debugger has been initialized and not before. If you have already set the breakpoints before, then you have to reset them after the debugger starts. One common strategy is to set the breakpoint on the main thread and then, once that has been hit, add the breakpoint on the background thread.
Debugger Isn’t Working: Disconnected
or Client not ready yet
This is usually a signal that the emulator instance is not properly connected with ADB and Android Studio. There are a few steps to try:
-
First, try uninstalling the app from within the emulator and then restarting the emulator completely. Try debugging again now.
-
Next, close the emulator again and also restart Android Studio. Start Android Studio and reload the emulator. Then try debugging again.
-
If you are using official emulator, try using Genymotion or vice-versa. Then try debugging again.
-
Open up
Tools => Android => Android SDK Manager
and see if there are any updates to the platform or SDK tools. Update any suggested changes within the manager and then restart your emulator and Android Studio. Then try debugging again.
References
- https://jaanus.com/debugging-http-on-an-android-phone-or-tablet-with-charles-proxy-for-fun-and-profit/
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Главная | Контакты | Администрирование | Программирование | Ссылки | |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|