- Методы лечения различных ошибок в Android Studio при разработке проекта
- Custom Application results in «Unable to create application» #1167
- Comments
- kspearrin commented Sep 7, 2018 •
- Please, provide the details below:
- Did you verify this is a real problem by searching the [NativeScript Forum (http://forum.nativescript.org) and the other open issues in this repo?
- Tell us about the problem
- Please provide the following version numbers that your issue occurs with:
- Did the error happen while the app was being constructed? (buildtime error)
- Did the error happen while the app was executing? (runtime error)
- Please tell us how to recreate the issue in as much detail as possible.
- Android: невозможно создать приложение
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Troubleshooting: Cannot Run on an Android Device or Emulator
- The app crashes because it cannot create the viewmodel instance #145
- Comments
- WasimReza2K8 commented Dec 5, 2020
- florina-muntenescu commented Dec 6, 2020
- Akiva-Grobman commented Dec 7, 2020 •
- Akiva-Grobman commented Dec 7, 2020
- hansRapnhap commented Dec 20, 2020 •
- Akiva-Grobman commented Dec 20, 2020
- flypadre commented Jan 23, 2021
- KJH1964 commented Jan 25, 2021 •
- Akiva-Grobman commented Jan 25, 2021
- SharifMrCreed commented Feb 22, 2021
Методы лечения различных ошибок в 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).
Источник
Custom Application results in «Unable to create application» #1167
Comments
kspearrin commented Sep 7, 2018 •
Please, provide the details below:
Did you verify this is a real problem by searching the [NativeScript Forum (http://forum.nativescript.org) and the other open issues in this repo?
Yes. Found this related issue, but seems to be using an old method: NativeScript/nativescript-dev-webpack#393
Tell us about the problem
Following this article, for creating custom application and activity with webpack:
Following all steps, yet when I run the app I get:
An uncaught Exception occurred on «main» thread.
java.lang.RuntimeException: Unable to create application com.tns.Application: com.tns.NativeScriptException: JavaScript object for Java ID 0 not found.
Attempting to call method onCreate
I can see my custom application and mainactivity classes in the generated vendor.js under platforms\android\app\src\main\assets\app .
I can also see the two generated java classes for MainActivity.java and Application.java in platforms\android\app\src\main\java\com\tns
I have added both new classes to appComponents in webpack.config.js.
My TypeScript classes:
Please provide the following version numbers that your issue occurs with:
- CLI: 4.2.2
- Cross-platform modules: 4.2.0
- Runtime(s): 4.2.0
Did the error happen while the app was being constructed? (buildtime error)
No, runtime error.
Did the error happen while the app was executing? (runtime error)
Please tell us how to recreate the issue in as much detail as possible.
I am using a relatively new app so there isn’t much generated outside of the standard template here.
The text was updated successfully, but these errors were encountered:
Источник
Android: невозможно создать приложение
Я переименовал свой пакет, и теперь я получаю эту странную ошибку:
Класс MyApplication находится в Application/app . В манифесте говорится:
Я попробовал перезагрузить, очистить. Не работает на эмуляторе или на реальном устройстве.
Что происходит на Земле?
ОТВЕТЫ
Ответ 1
Предположим, что ваш базовый пакет проектов действительно Application , как вы сказали в manifest .
Если ваш класс MyApplication находится внутри этого пакета (объявление пакета класса package Application; ), то элемент Application в вашем androidManifest.xml должен выглядеть как
Если этот класс MyApplication находится внутри пакета Application.app ( package Application.app; ), то в манифесте вы должны написать:
Если вы не расширили android.app.Application (у вас нет класса MyApplication extends android.app.Application ), просто хотите установить имя для своего приложения, удалите его из этого атрибута, так как он говорит компилятору, что есть расширение Application , которое должно быть создано вместо стандартного android.app.Application .
И, наконец, если первое предположение неверно, и вы по какой-либо причине изменили объявление пакета в элементе androidManifest manifest , отмените его или обновите свои классы в этом пакете.
Ответ 2
Для меня проблема заключалась в мгновенном запуске. Отключение этого решения проблемы.
Будет обновлено, если я найду решение для повторного включения и создания его работы.
Ответ 3
этот ответ помог мне, в основном переименуйте свой lib в libs, если вы используете SDK 17+ fooobar.com/questions/285156/.
Ответ 4
В моем случае я изменил уровень соответствия JAVA-компилятора с 1.7 до 1.6, и проблема была решена.
Ответ 5
убедитесь, что все ссылки в манифесте обновлены, чтобы отразить ваше новое имя пакета.
Ответ 6
Должен package=»Application» быть package=»MyApplication» ?
Ответ 7
Вам нужно исправить атрибут android:name . Такая же проблема упомянута в ClassNotFoundException после изменения имени приложения на Android
Источник
Troubleshooting: Cannot Run on an Android Device or Emulator
If you get any of the following error dialog boxes, use the suggested steps following each error box:
This error may occur for either of the following reasons:
- You try to install your application on your Android device using the same package name as a previously-installed application, but you use a signing certificate different from the certificate of the installed application. This is the case when you change the platform configuration of your application between Debug and Application Store, or when you configure a new certificate in the Provisioning options page for the Application Store platform configuration.
To solve this issue, do either of the following:
- Manually uninstall the previously-installed application from your Android device.
- Configure RAD Studio to perform a clean install every time that you run your application.
- You try to install your application on your Android device using the Application Storeplatform configuration but you do not have a certificate configured in the Provisioning options page for the Application Store platform configuration.
looks like the path to your Adb executable:
- Open the SDK Manager and verify that the value of the Adb location field is correct in the SDK Properties of your Android SDK.
- If the value is marked with a warning icon, you must update the path so that it points to your Adb executable (Android Debug Bridge).
where is the port number being used by the Android gdbserver:
- Power off or restart your Android device and then run your application again.
- Choose another debug port:
- Select Run >Parameters and enter the following in the Parameters field: -debugport= where is an alternate debug port, such as 54321.
- Then click OK.
Источник
The app crashes because it cannot create the viewmodel instance #145
Comments
WasimReza2K8 commented Dec 5, 2020
After running the code I got the following error message from android studio. Basically, it cannot create the viewmodel because it has a dependency on the application reference. However, the initialization did not mention from where the viewmodel collects the dependency.
java.lang.RuntimeException: Unable to start activity ComponentInfo
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.android.roomwordssample.WordViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.example.android.roomwordssample.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.InstantiationException: java.lang.Class has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
The text was updated successfully, but these errors were encountered:
florina-muntenescu commented Dec 6, 2020
Which version of the codelab is this, Java or Kotlin?
Akiva-Grobman commented Dec 7, 2020 •
I had the same problem(in java). This solved it:
// old code
mWordViewModel = new ViewModelProvider(this).get(WordViewModel.class);
// new code
mWordViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(WordViewModel.class);
Akiva-Grobman commented Dec 7, 2020
Check out my previous comment and see if it help.
hansRapnhap commented Dec 20, 2020 •
Akiva’s solution helps. Why do you not include that in the github code and in the
https://developer.android.com/codelabs/android-room-with-a-view
pages?
I followed the complete course, and ended in loosing time by this not working code part !
Akiva-Grobman commented Dec 20, 2020
Give them some time, I’m sure it will be fixed.
flypadre commented Jan 23, 2021
For anyone who doesn’t know the line of code can be found in MainActivity.java
KJH1964 commented Jan 25, 2021 •
Thanks, I’d figured out it was in that line of code, just didn’t know what to do about it. I’d tracked down the exception being thrown in the ActivityThread.java class when that line was executed. But it would have taken me a long time to get from there to the change above. As hansRapnhap says it would be nice if they updated GitHub. Still I learnt some more about tracking down bugs, even if I didn’t fix it.
Akiva-Grobman commented Jan 25, 2021
Thanks, I’d figured out it was in that line of code, just didn’t know what to do about it. I’d tracked down the exception being thrown in the ActivityThread.java class when that line was executed. But it would have taken me a long time to get from there to the change above. As hansRapnhap says it would be nice if they updated GitHub. Still I learnt some more about tracking down bugs, even if I didn’t fix it.
I’ve made a PR but it doesn’t pass a firebase test so they didn’t except it.
SharifMrCreed commented Feb 22, 2021
I had the same problem(in java). This solved it:
// old code
mWordViewModel = new ViewModelProvider(this).get(WordViewModel.class);
// new code
mWordViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(WordViewModel.class);
Man thanx alot for this been at it for almost 2 days to thing it would be solved so simply like this.
Источник