Java.lang.RuntimeException: невозможно создать экземпляр активности ComponentInfo{com.example.uow/com.example.uow.MainActivity}

Приложение запускается как на физических, так и на виртуальных устройствах, но только на секунду, показывая пустой белый экран, а затем показывает диалоговое окно, в котором xxx перестал работать.

используя последний флаттер и последние пакеты.

Код отладки консоли VS с физическим устройством:

Запуск lib\main.dart на Nexus 6P в режиме отладки... Формат параметра неверно - √ Встроенная сборка\приложение\выходы\флуттер-апк\приложение-отладка.апк. E/AndroidRuntime(18660): НЕИСПРАВНОЕ ИСКЛЮЧЕНИЕ: основной E/AndroidRuntime(18660): Процесс: com.example.uow, PID: 18660 E/AndroidRuntime(18660): java.lang.RuntimeException: невозможно создание экземпляра активности ComponentInfo{com.example.uow/com.example.uow.MainActivity}: java.lang.ClassNotFoundException: класс не найден «com.example.uow.MainActivity» по пути: DexPathList[[zip-файл "/data/app/~~qbQtrDUlPVDpUgF2_cqf1Q==/com.example.uow-zqtGS9vJh4yr2iNiXDdufQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~qbQtrDUlPVDpUgF2_cqf1Q==/com.example.uow-zqtGS9vJ h4yr2iNiXDdufQ= =/lib/arm64, /data/app/~~qbQtrDUlPVDpUgF2_cqf1Q==/com.example.uow-zqtGS9vJh4yr2iNiXDdufQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system_ext/lib64]] E/AndroidRuntime(18660): в android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3582) E/AndroidRuntime (18660): в android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3813) E/AndroidRuntime (18660): в android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101) E/AndroidRuntime (18660): в android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) E/AndroidRuntime (18660): в android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) E/AndroidRuntime (18660): в android.app.ActivityThread$H.handleMessage(ActivityThread.java:2308) E/AndroidRuntime (18660): в android.os.Handler.dispatchMessage(Handler.java:106) E/AndroidRuntime (18660): в android.os.Looper.loopOnce(Looper.java:201) E/AndroidRuntime(18660): на android.os.Looper.loop(Looper.java:288) E/AndroidRuntime(18660): в android.app.ActivityThread.main(ActivityThread.java:7898) E/AndroidRuntime(18660): в java.lang.reflect.Method.invoke(собственный Метод) E/AndroidRuntime(18660): в com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) E/AndroidRuntime (18660): в com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) E/AndroidRuntime(18660): причина: java.lang.ClassNotFoundException: Не найден класс "com.example.uow.MainActivity" по пути: DexPathList[[zip-файл "/data/app/~~qbQtrDUlPVDpUgF2_cqf1Q==/com.example.uow-zqtGS9vJh4yr2iNiXDdufQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~qbQtrDUlPVDpUgF2_cqf1Q==/com.example.uow-zqtGS9vJ h4yr2iNiXDdufQ= =/lib/arm64, /data/app/~~qbQtrDUlPVDpUgF2_cqf1Q==/com.example.uow-zqtGS9vJh4yr2iNiXDdufQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system_ext/lib64]] E/AndroidRuntime(18660): в dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:259) E/AndroidRuntime (18660): в java.lang.ClassLoader.loadClass(ClassLoader.java:379) E/AndroidRuntime (18660): в java.lang.ClassLoader.loadClass(ClassLoader.java:312) E/AndroidRuntime (18660): в android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95) E/AndroidRuntime (18660): в androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45) E/AndroidRuntime (18660): в android.app.Instrumentation.newActivity(Instrumentation.java:1328) E/AndroidRuntime (18660): в android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3569) E/AndroidRuntime(18660): ... еще 12 Ошибка ожидания отладки подключение: программа чтения журнала неожиданно остановилась Ошибка запуска приложение на Nexus 6P. Вышел (сигтерм)

Манифест:

<manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.uow">
  <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
  <uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION"/>
  <application android:name = "${applicationName}" android:label = "uow" android:icon = "@mipmap/ic_launcher">
    <meta-data android:name = "com.google.android.geo.API_KEY" android:value = "YOUR_API_KEY"/>

    <activity android:name = ".MainActivity" android:exported = "true" android:launchMode = "singleTop" android:theme = "@style/LaunchTheme" android:configChanges = "orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated = "true" android:windowSoftInputMode = "adjustResize">
      <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
      <meta-data android:name = "io.flutter.embedding.android.NormalTheme" android:resource = "@style/NormalTheme" />
      <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
      <meta-data android:name = "io.flutter.embedding.android.SplashScreenDrawable" android:resource = "@drawable/launch_background" />
      <intent-filter>
        <action android:name = "android.intent.action.MAIN"/>
        <category android:name = "android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
    <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
    <meta-data android:name = "flutterEmbedding" android:value = "2" />
  </application>
</manifest>

приложение/build.gradle:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services' 

android {
    compileSdkVersion 33

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.uow"
        minSdkVersion 27
        targetSdkVersion 33
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
       
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics'
    implementation platform('com.google.firebase:firebase-bom:31.1.0')
}

проект build.gradle:

buildscript {
    ext.kotlin_version = '1.7.21'
    repositories {
        google()
        jcenter()
        mavenCentral()  // Maven Central repository
    }

    dependencies {
        classpath "com.android.tools.build:gradle:7.0.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.13'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()  // Maven Central repository
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

град.свойства:

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
org.gradle.java.home=C:\\Program Files\\Android\\Android Studio\\jre

свойства gradle-обертки:

#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip

флаттер доктор:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.3.8, on Microsoft Windows [Version 10.0.22621.819], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[√] Chrome - develop for the web
[X] Visual Studio - develop for Windows
    X Visual Studio not installed; this is necessary for Windows development.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.3)
[√] VS Code (version 1.73.1)
[√] Connected device (4 available)
[√] HTTP Host Availability

! Doctor found issues in 1 category.

Похоже проблема с эмулятором, можете попробовать запустить приложение на другом устройстве?

Fahmida 24.11.2022 05:58
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
1
268
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Я исправил проблему, изменив все файлы, связанные с Gradle, на те, которыми я делюсь ниже. проблема, похоже, была связана с версией gradle. Надеюсь это поможет.

построить.градле:

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()  // Maven Central repository
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.1.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.13'
    }
}
allprojects {
    repositories {
        google()
        mavenCentral()  // Maven Central repository
    }
}
rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
    delete rootProject.buildDir
}


уровень приложения build.gradle:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android' 

android {
    compileSdkVersion 33

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.uow"
        minSdkVersion 27
        targetSdkVersion 33
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        multiDexEnabled true
       
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-analytics'
    implementation platform('com.google.firebase:firebase-bom:31.1.0')
     implementation("androidx.multidex:multidex:2.0.1")
}

свойства градиента:


org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
org.gradle.java.home=C:\\Program Files\\Android\\Android Studio\\jre

свойства оболочки gradle:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Манифест андроида:

<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
 package = "com.example.uow"
 xmlns:tools = "http://schemas.android.com/tools">
  <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
  <uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION"/>
  <application 
      android:name = "${applicationName}" 
      android:label = "uow" 
      android:icon = "@mipmap/ic_launcher">


    <activity 
        android:name = ".MainActivity" 
        android:exported = "true" 
        android:launchMode = "singleTop" 
        android:theme = "@style/LaunchTheme" 
        android:configChanges = "orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" 
        android:hardwareAccelerated = "true" 
        android:windowSoftInputMode = "adjustResize">
      <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
      <meta-data android:name = "io.flutter.embedding.android.NormalTheme" android:resource = "@style/NormalTheme" />
      <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
      <meta-data 
          android:name = "io.flutter.embedding.android.NormalTheme" 
          android:resource = "@style/NormalTheme" />
      <intent-filter>
        <action android:name = "android.intent.action.MAIN"/>
        <category android:name = "android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
    <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
    <meta-data android:name = "flutterEmbedding" android:value = "2" />
  </application>
</manifest>


основная деятельность:



package com.example.uow

import io.flutter.embedding.android.FlutterActivity

class MainActivity: FlutterActivity() {
}

Другие вопросы по теме