Методы лечения различных ошибок в 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).
Источник
How to resolve build path errors?
If I run my project this error will come build path problem how to solve this error.
- Description Resource Path Location Type Project ‘videothumb’ is missing required source folder: ‘gen’ videothumb Build path Build Path Problem
- The project cannot be built until build path errors are resolved videothumb Unknown Java Problem
Can any one help me?
5 Answers 5
Try to clean project and if it still doesn’t help close and then open project.
IF you are using eclipse then do as follows:
- right click your project.
- select build path—>configure build path .
- update all the broken links in all 4 tabs.
- Go to project—>clean [project will be found at top menu of eclipse.]
- Clean your project.
Its done. For any further explanation comment on my answer.
Hope this helps.
Edit:
As you can see i’m at source tab of configure build path and i have only one folder here named ATalk/Src. likewise you can have number of folders.
Check for red cross mark on folder. if its there then your folder path is wrong means link is broken for that folder.
Same way you can check in Libraries tab. There you will find list of jars in your project. If any of them have red cross then its path is missing. So update all such red cross paths.
As you can see i dont have a red cross on my folder means it is at correct location.
Hope you get my point.
EDIT:
I just noticed that, according to your screenshot, the problem seems to be that the adb tool is not found. Now I might be wrong but I think that as of Android 2.3 (maybe even earlier) the adb tool is expected to be in [path-to-your-sdk]/platform-tools folder, not in the [path-to-your-sdk]/tools folder. The later path was used in earlier SDK’s and your problem might be caused by such a simple thing that you have an outdated Android plugin in Eclipse.
OLD, IRRELEVANT ANSWER:
I’ve seen these kind of issues in Eclipse environments when I have some kind of error in my XML files. Malformed errors (that violate the rules of the XML structure) are often treated as «syntax errors» and are shown directly when you write them or when you try to build your application.
Other errors, however, like giving invalid references (giving a dimension where an integer is expected, for example) are not always highlighted with file name and failing line number (I’m not sure if this is bug in Eclipse’s android plugin or even if it’s a bug at all).
These kind of errors you’ll have to hunt down manually and rebuild your project (as dcave555 sugested). This is really boring work if you have many XML files with many changes in
Источник
Android APK path is not specified for module
I have a problem. When i try to launch my project i’ve got error :
I follow to this answer APK path is not specified for module «Example-Example» but that no give me result. Any more ideas?
5 Answers 5
Finally I founded a solution.
- Open Project structure
- Click on Modules tab
- Expand your project and click on Android
- On right side click on Packaging tab (Compiler on older versions of Android Studio)
- Looking for «APK path» field
- Click on . and choose your project root folder(that contains bin/,gen/,res/ folders
- Copy path into your clipboard
- Close choose path dialog
- Paste copied path into APK path field.
- Add to path text \bin
- Click Apply and Ok
In the end you must have a path :
Try to build your project.
may be it helps for someone .
Note : For Android Studio use this answer.
Could not use the accepted answer in my Android Studio (0.6.1) because I couldn’t find the «Compiler» tab. I suppose that this structure is for Intelij. Nevertheless, it pointed me to the right solution:
My Project included some LIB modules besides the main APK module and by setting all modules to use the same Compiler output directory fixed the error. In order to do so you just need to follow these steps:
- Open Project structure (F4 on one of the modules in the project explorer)
- Click on Project tab on the left
- Define «Project compiler output:» as YOUR_PROJECT_PATH\out (or any folder you want)
- Click on Modules tab on the left
- Go over all your modules and verify that under the Paths tab the Compiler output is set to «Inherit project compile output path»
- Thats it.
Источник
Your project path contains non-ASCII characters android studio
I was installing android studio, but I have this problem when the program is starting:
Error:(1, 0) Your project path contains non-ASCII characters. This will most likely cause the build to fail on Windows. Please move your project to a different directory. See http://b.android.com/95744 for details.
This warning can be disabled by using the command line flag -Dcom.android.build.gradle.overridePathCheck=true, or adding the line ‘com.android.build.gradle.overridePathCheck=true’ to gradle.properties file in the project directory.
13 Answers 13
I solved this issue by adding this line
As this message said
I did create a symbol link (c:\android-sdk) in windows 10 and resolved:
mklink /D «c:\android-sdk» «C:\Users\Clézio\android-sdk»
I have the same problem.then I create a new project and the path only use English alphabet,the problem is resolved.
I meet this problem and find there are some Chinese characters in my path. After change these characters into English , the problem solved.
If you face with the problem at the first time installing Android Studio on your computer.
mklink /D «c:\Android-Sdk» «C:\Users\ **YOUR-USERNAME** \AppData\Local\Android\sdk»
Go to «C:\Users\ YOUR-USERNAME \AppData\Local\» path and create Android\sdk folders inside it.
After that you can continue installation.
Your project path contains Chinese characters,
Please rename the path English characters:
What I actually did was redirect (I don’t actually know the term) the path to my other user (my path was C:\Users\Keith Peñas\ etc.) then, I thought that I had this Spanish letter on, so I redirected the path to my other user, in this case it was (C:\Users\Keith). Then I had another problem: it was somewhat like «Your path cannot be with the rooted path». So I made a folder with the name of my app and then it worked!
Another problem I encountered was: «your path contains white space etc.» and it was from my other disk.
Hope this helps!
The path location must not contain á,à,â, and similars. Chinese characters or any other diferent than the usual alphabetical characters. For example, my path was C:\Users\Vinícius\AndroidStudioProjects\MyApplication .But my user name had the letter í. So I create a folder ‘custom2222’ and change the path to C:\custom2222\MyApplication
I also encountered this problem, and I have to change the folder name from Chinese to English. Pity that current gradle build tool does not support Unicode names.
I created a symbol link like described by Clézio before. However, I had to specify a suitable encoding (e.g chcp 65001) in command line before.
If you have your SDK installed under Path C:\Users[USER]\AppData. you may have to run command line with administrativ priviledges.
This error occur because of path of project. Change your project path wiht way which dont contain nonAscii character.
Источник
Where is android studio building my .apk file?
I’ve been rebuilding my project from the ground up, so there’s been a lot of problems with it. At the moment, everything’s working great, except that when I try to run the app, I get the message ‘Local path doesn’t exist.’, where the local path is pointing at the path: AndroidStudioProjects\MyProject\MyProject..\build\production\MyProject.apk, and true enough, there is no .apk file at that location, or indeed anywhere else in the project filesystem.
However, I can build the app with no problems, and running gradlew packageDebug gives me the message ‘build successful‘, so .apks should be being generated. My question is, where are they going, or if they aren’t being generated, why not?
Where is the build path of each module set? I’m somewhat confused because the Project Structure->Facets->Android->Compiler settings, Project Structure->Modules->Paths->Compiler Output, build.gradle, and MyProject.iml all seem to have something to do with the build path, but I don’t quite understand how they relate
edit: I know where it should be, but it’s not there so I want to know how to change the build path
edit 2: For some reason running gradlew build does create .apks, but not building or running from inside the program
edit 3: Here’s my gradlew build output, note that it does build successfully:
Источник