- Android Studio 3.1.4: missing classes and uncorrect Blueprint displaying
- Similar StackOverflow questions — Android support library
- Using implementation ‘com.android.support:appcompat-v7:27.1.1
- Errors opening the Layout Editor
- Blueprint problems — What is in my UI?
- Android Studio — Missing class declarations in target API’s classes
- Методы лечения различных ошибок в Android Studio при разработке проекта
- Why Android Studio doesn’t allow me to create Java Classes?
- 4 Answers 4
Android Studio 3.1.4: missing classes and uncorrect Blueprint displaying
I use Android Studio 3.1.4 on Ubuntu 18.04.1. I wanted to quickly create the UI of the main (default) activity so I opened the Layout Editor. Some errors have occurred. Then I tried to add a button: it doesn’t seem to be displayed in the Blueprint (and the ConstraintLayout is weirdly displayed too).
Similar StackOverflow questions — Android support library
Similar questions have been asked in StackOverflow. The answers were to use a different version of the Android support library. Currently, I’m using this version:
implementation ‘com.android.support:appcompat-v7:28.0.0-rc01’ (file: build.gradle(Module: app) ).
Indeed, even if Android Studio recommended me to use 28.0.0-rc02 , I don’t see it in this list: https://mvnrepository.com/artifact/com.android.support/design?repo=google .
By the way, I encountered all of the mentionned bugs with 28.0.0-rc02 too. In résumé, I encounter all of these bugs with 28.0.0-rc01 (currently used) and 28.0.0-rc02 . I didn’t try other versions for the moment.
Using implementation ‘com.android.support:appcompat-v7:27.1.1
With implementation ‘com.android.support:appcompat-v7:27.1.1’ , all the problems are solved. However:
It’s not the last version (https://mvnrepository.com/artifact/com.android.support/design?repo=google indicates the last version is: 28.0.0-rc01 , Android Studio indicates it’s 28.0.0-rc02 — both bug)
Android studio underlines in red my implementation instruction as follows:
Errors opening the Layout Editor
Failed to load AppCompat ActionBar with unknown error.
- The following classes could not be instantiated
— android.support.v7.widget.ActionBarContainer (Open Class, Show Exception, Clear Cache) — android.support.v7.widget.ActionBarContextView (Open Class, Show Exception, Clear Cache) — android.support.v7.app.WindowDecorActionBar (Open Class, Show Exception, Clear Cache)
Exception Details:
java.lang.ClassNotFoundException: android.view.View$OnUnhandledKeyEventListener at org.jetbrains.android.uipreview.ModuleClassLoader.load(ModuleClassLoader.java:180) at com.android.tools.idea.rendering.RenderClassLoader.findClass(RenderClassLoader.java:61) at org.jetbrains.android.uipreview.ModuleClassLoader.findClass(ModuleClassLoader.java:118) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at org.jetbrains.android.uipreview.ModuleClassLoader.loadClass(ModuleClassLoader.java:213) at android.support.v7.widget.ActionBarContainer.(ActionBarContainer.java:62) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:481) at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:264) at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:222) at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:209) at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:337) at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:348) at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:248) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:863) at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72) at android.view.LayoutInflater.rInflate(LayoutInflater.java:837) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at com.android.layoutlib.bridge.bars.BridgeActionBar.(BridgeActionBar.java:89) at com.android.layoutlib.bridge.bars.AppCompatActionBar.(AppCompatActionBar.java:68) at com.android.layoutlib.bridge.impl.Layout.createActionBar(Layout.java:277) at com.android.layoutlib.bridge.impl.Layout.(Layout.java:161) at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:288) at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:384) at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:193) at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:544) at com.android.tools.idea.rendering.RenderTask.lambda$inflate$3(RenderTask.java:678) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)
Blueprint problems — What is in my UI?
For the moment, nothing apart the root component (a ConstraintLayout instance), as you can see (note that the ConstraintLayout seems to be represented as a very little square in the Blueprint — that’s a Blueprint problem, no?):
If I drag’n drop a button with the text «TEST TEST TEST» in the Blueprint, I get this (note that the button. doesn’t really appear, only a weird thing is displayed inside the square):
I clicked several time on this square with a weird thing inside. I got this new exception:
Missing Constraints in ConstraintLayout
This view is not constrained vertically: at runtime it will jump to the top unless you add a vertical constraint The layout editor allows you to place widgets anywhere on the canvas, and it records the current position with designtime attributes (such as layout_editor_absoluteX). These attributes are not applied at runtime, so if you push your layout on a device, the widgets may appear in a different location than shown in the editor. To fix this, make sure a widget has both horizontal and vertical constraints by dragging from the edge connections.
Источник
Android Studio — Missing class declarations in target API’s classes
I’m using Android Studio 2.2.3, currently developing an app with the following build conditions as found in app’s build.gradle file:
As you can see, the app is targeting API 24. I’ve installed (I think) every required SDK components:
- Android SDK Build-Tools 24.0.3
- Sources for Android 24
- Android SDK Platform 24
- Google APIs (for API Level 24)
In my app, I’m using one of the methods of the native AccountManager class. If I jump to the declaration of the AccountManager.addAccountExplicitly() method, this is what I can see:
As you can see on the scrolling area on right side, several declarations are missing, like they would not be imported to the class. For example, on line 733 the mService field has a class type which Android Studio cannot find, so the method is missing too (says ‘Cannot resolve method. ‘ when hovering the mouse over it). And this is how the field’s missing class type looks like (on line 269):
I’ve tried to reinstall every SDK component, even tried File > Invalidate Caches / Restart several times, but the problem is still there. I didn’t find anything similar to this on SO, nor anywhere else. Do someone know what is happening?
UPDATE 1: After the answer of DKIT I’ve looked around in the Android Developers class reference, searching for the IAccountManager class, but it’s nowhere — I have no idea what this could be and what would it refer to. Moreover, the AccountManager class was introduced in API Level 5 with most of it’s methods, including addAccountExplicitly() ; so I cannot see any reason why it would not exist on any nowadays common device.
By the way, the following classes are «unimported» too in AccountManager (technically they are in the import section, but their declarations are also missing). Maybe this helps.
- android.annotation.NonNull
- android.annotation.RequiresPermission
- android.annotation.Size
- android.annotation.SystemApi (as seen also on Image 2 at line 259)
- com.google.android.collect.Maps
UPDATE 2: The reason why I’m missing so much the inner components in native Android classes is that I would like to know what is happening inside them exactly. I think it would be really simple to look on the working of Android components right here, in Android Studio, however it is possible that this use case / feature is existing somewhere else on the internet I don’t know about. 😀
Thanks for Ashwin Mothilal in helping me to make this clear for everyone! 😉
Источник
Методы лечения различных ошибок в 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).
Источник
Why Android Studio doesn’t allow me to create Java Classes?
Starting from the update to Android Studio 2 days ago, it doesn’t let me create Java classes anymore. And the current classes now have a strange symbol.
I tried to export and import many times with different configuration but they never worked. Any advice?
Here are two screenshots:
Here is the structure of my Android Studio project. AndroidManifest is in the right place:
4 Answers 4
Right click on the src folder, Mark Directory As -> Source Root.
Android Studio 1.0 Update:
In project view of Android Studio please check for “java” folder under src.
Usually there will be two folders automatically created by Android Studio under src —
- androidTest (This is used for writing test cases),
- main (This is used for writing your application source.)
Each of these should contain a «java» folder.
If java folder is not there, you can create it with right click on main (or androidTest) as shown below
To add a new java class, please right click on the «java folder» and select «java class».
Источник