android 尽管添加了NavHostFragment,但应用程序不工作

jtjikinw  于 2023-03-06  发布在  Android
关注(0)|答案(1)|浏览(178)

我正在复数视觉课程中开发Note Keeper应用程序。我在应用程序上有两个Activity,每当我在模拟器上运行应用程序时,它显示构建成功,但应用程序未启动。我从导航图中注意到Activity xml文件中没有NavHostFragment,因此我尝试添加它,但Activity xml文件中一直出现渲染问题。
每当我添加navhostfragment时,我的activity总是出现渲染问题和其他错误。我可以修复渲染问题。但是当我在模拟器上运行应用时,我会遇到这个错误。

Launching 'app' on Pixel 6 API 33.
Install successfully finished in 6 s 713 ms.
$ adb shell am start -n "com.example.nokeeper4/com.example.nokeeper4.NoteListActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 3595 on device 'Pixel_6_API_33 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ample.nokeeper4: Late-enabling -Xcheck:jni
W/ample.nokeeper4: Unexpected CPU variant for x86: x86_64.
    Known variants: atom, sandybridge, silvermont, kabylake, default
W/ample.nokeeper4: Suspending all threads took: 10.595ms
W/ample.nokeeper4: Suspending all threads took: 10.339ms
W/ample.nokeeper4: Suspending all threads took: 42.020ms
V/studio.deploy: Startup agent attached to VM
W/re-initialized>: type=1400 audit(0.0:37): avc: granted { execute } for path="/data/data/com.example.nokeeper4/code_cache/startup_agents/8dee6a62-agent.so" dev="dm-33" ino=132681 scontext=u:r:untrusted_app:s0:c159,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c159,c256,c512,c768 tclass=file app=com.example.nokeeper4
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-b5380c1f.jar
W/ample.nokeeper4: DexFile /data/data/com.example.nokeeper4/code_cache/.studio/instruments-b5380c1f.jar is in boot class path but is not in a known location
V/studio.deploy: ModifyParameterTransform failed: Landroid/app/ApplicationLoaders;
W/ample.nokeeper4: Current dex file has more than one class in it. Calling RetransformClasses on this class might fail if no transformations are applied to it!
W/ample.nokeeper4: Current dex file has more than one class in it. Calling RetransformClasses on this class might fail if no transformations are applied to it!
W/ample.nokeeper4: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/ample.nokeeper4: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
W/ample.nokeeper4: Current dex file has more than one class in it. Calling RetransformClasses on this class might fail if no transformations are applied to it!
W/ample.nokeeper4: Current dex file has more than one class in it. Calling RetransformClasses on this class might fail if no transformations are applied to it!
W/ample.nokeeper4: Current dex file has more than one class in it. Calling RetransformClasses on this class might fail if no transformations are applied to it!
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10159; state: ENABLED
D/nativeloader: Configuring classloader-namespace for other apk /system_ext/framework/androidx.window.extensions.jar. target_sdk_version=33, uses_libraries=ALL, library_path=/data/app/~~ff6ca8L6X6Un-NPgSDzZEA==/com.example.nokeeper4-oaGPocSkqAqijVL_2tY9rw==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.nokeeper4
D/nativeloader: Configuring classloader-namespace for other apk /system_ext/framework/androidx.window.sidecar.jar. target_sdk_version=33, uses_libraries=ALL, library_path=/data/app/~~ff6ca8L6X6Un-NPgSDzZEA==/com.example.nokeeper4-oaGPocSkqAqijVL_2tY9rw==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.nokeeper4
W/ziparchive: Unable to open '/data/app/~~ff6ca8L6X6Un-NPgSDzZEA==/com.example.nokeeper4-oaGPocSkqAqijVL_2tY9rw==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~ff6ca8L6X6Un-NPgSDzZEA==/com.example.nokeeper4-oaGPocSkqAqijVL_2tY9rw==/base.dm': No such file or directory
D/nativeloader: Configuring classloader-namespace for other apk /data/app/~~ff6ca8L6X6Un-NPgSDzZEA==/com.example.nokeeper4-oaGPocSkqAqijVL_2tY9rw==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~ff6ca8L6X6Un-NPgSDzZEA==/com.example.nokeeper4-oaGPocSkqAqijVL_2tY9rw==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.nokeeper4
V/GraphicsEnvironment: ANGLE Developer option for 'com.example.nokeeper4' set to: 'default'
V/GraphicsEnvironment: ANGLE GameManagerService for com.example.nokeeper4: false
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/ample.nokeeper4: Verification of void androidx.emoji2.text.EmojiCompatInitializer.delayUntilFirstResume(android.content.Context) took 105.765ms (236.37 bytecodes/s) (1976B approximate peak alloc)
W/ample.nokeeper4: Verification of boolean androidx.arch.core.executor.ArchTaskExecutor.isMainThread() took 111.201ms (62.95 bytecodes/s) (1440B approximate peak alloc)
W/ample.nokeeper4: Verification of void androidx.emoji2.text.EmojiCompat$Config.<init>(androidx.emoji2.text.EmojiCompat$MetadataRepoLoader) took 154.878ms (167.87 bytecodes/s) (1896B approximate peak alloc)
W/ample.nokeeper4: Verification of void androidx.activity.ComponentActivity.<init>() took 116.301ms (1573.50 bytecodes/s) (7392B approximate peak alloc)
D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
W/ample.nokeeper4: Verification of void androidx.appcompat.app.AppCompatActivity.<init>(int) took 237.003ms (29.54 bytecodes/s) (1376B approximate peak alloc)
D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
D/AppCompatDelegate: Checking for metadata for AppLocalesMetadataHolderService : Service not found
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.nokeeper4, PID: 3595
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nokeeper4/com.example.nokeeper4.NoteListActivity}: kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3645)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7872)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
     Caused by: kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
        at com.example.nokeeper4.NoteListActivity.onCreate(NoteListActivity.kt:19)
        at android.app.Activity.performCreate(Activity.java:8305)
        at android.app.Activity.performCreate(Activity.java:8284)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1417)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3626)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loopOnce(Looper.java:201) 
        at android.os.Looper.loop(Looper.java:288) 
        at android.app.ActivityThread.main(ActivityThread.java:7872) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) 
W/System: A resource failed to call close. 
I/Process: Sending signal. PID: 3595 SIG: 9

下面是我的main Activityxml的代码:

<?xml version="1.0" encoding="utf-8"?\>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"\>

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.Nokeeper4.AppBarOverlay">
    
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/Theme.Nokeeper4.PopupOverlay" />
    
    </com.google.android.material.appbar.AppBarLayout>
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_frag"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:navGraph="@navigation/nav_graph2"
        tools:layout="@layout/activity_main"/>
    
    
    <include
        android:id="@+id/contentMain"
        layout="@layout/content_main" />

</androidx.coordinatorlayout.widget.CoordinatorLayout\>

注意事项列表活动xml文件e:

<?xml version="1.0" encoding="utf-8"?\>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NoteListActivity"\>

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="100dp"
        android:layout_width="match_parent">
    
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="?attr/actionBarSize"
            android:layout_width="match_parent" />
    
    </com.google.android.material.appbar.AppBarLayout>
    
    
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        android:contentDescription="@string/new_note"
        android:src="@drawable/baseline_add_white_24"
        app:backgroundTint="#9C27B0" />
    
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_frag"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:navGraph="@navigation/nav_graph2"
        tools:layout="@layout/activity_note_list"/>
    
    <include
        android:id="@+id/contentNoteList"
        layout="@layout/content_note_list" />

</androidx.coordinatorlayout.widget.CoordinatorLayout\>

下面是我mainActivity.kt文件

class MainActivity : AppCompatActivity() {

    private var notePosition = POSITION_NOT_SET
    private lateinit var spinnerCourses:  Spinner
    private lateinit var textNoteTitle: EditText
    private lateinit var textNoteText: EditText

    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(binding.root)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setSupportActionBar(binding.toolbar)
        spinnerCourses = findViewById(R.id.spinnerCourses)
        textNoteTitle = findViewById(R.id.textNoteTitle)
        textNoteText = findViewById(R.id.textNoteText)



        val adapterCourses = ArrayAdapter<CourseInfo>(this,
                android.R.layout.simple_spinner_item,
                DataManager.courses.values.toList())
        adapterCourses.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerCourses.adapter = adapterCourses

        notePosition = savedInstanceState?.getInt(NOTE_POSITION, POSITION_NOT_SET) ?:
            intent.getIntExtra(NOTE_POSITION,POSITION_NOT_SET)

        if (notePosition != POSITION_NOT_SET)
            displayNote()
        else{
            DataManager.notes.add(NoteInfo())
            notePosition = DataManager.notes.lastIndex
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt(NOTE_POSITION, notePosition)
    }

    private fun displayNote() {
        val note = DataManager.notes[notePosition]
        textNoteTitle.setText(note.title)
        textNoteText.setText(note.text)

        val coursePosition = DataManager.courses.values.indexOf(note.course)
        spinnerCourses.setSelection(coursePosition)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            R.id.action_next ->{
                moveNext()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun moveNext() {
        ++notePosition
        displayNote()
        invalidateOptionsMenu()
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        if(notePosition >= DataManager.notes.lastIndex){
            val menuItem = menu?.findItem(R.id.action_next)
            if(menuItem != null){
                menuItem.icon = getDrawable(R.drawable.baseline_block_black_24)
                menuItem.isEnabled = false
            }
        }
        return super.onPrepareOptionsMenu(menu)
        
    }

    override fun onPause() {
        super.onPause()
        saveNote()
    }

    private fun saveNote() {
        val note = DataManager.notes[notePosition]
        note.title = textNoteTitle.text.toString()
        note.text = textNoteText.text.toString()
        note.course = spinnerCourses.selectedItem as CourseInfo
    }
}

备注列表活动.kt

class NoteListActivity : AppCompatActivity() {

    private lateinit var binding: ActivityNoteListBinding
    private lateinit var listNotes: ListView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        setContentView(binding.root)
        binding = ActivityNoteListBinding.inflate(layoutInflater)
        listNotes = findViewById(R.id.listNotes)

        binding.fab.setOnClickListener {
            val activityIntent = Intent(this, MainActivity::class.java)
            startActivity(activityIntent)
        }
        listNotes.adapter = ArrayAdapter(
            this,
            android.R.layout.simple_list_item_1,
            DataManager.notes)

        listNotes.setOnItemClickListener { _, _, position, _ ->
            val activityIntent = Intent(this, MainActivity::class.java)
            activityIntent.putExtra(NOTE_POSITION, position)
            startActivity(activityIntent)

        }
    }

    override fun onResume() {
        super.onResume()
        (listNotes.adapter as ArrayAdapter<*>).notifyDataSetChanged()
    }
}
wpx232ag

wpx232ag1#

您似乎创建了一个循环。
tools:layout不应引用您所在的文件。
因此,从androidx.fragment.app.FragmentContainerView中删除两个活动XML文件中的tools

相关问题