“尝试在空对象引用上调用虚拟方法'android.content.Context android.content.Context.getApplicationContext()'”

"Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference"

提问人:Arsh Ansari 提问时间:8/15/2021 最后编辑:Arsh Ansari 更新时间:8/15/2021 访问量:1736

问:

我是堆栈溢出的新手,所以请原谅问题的格式不正确,我在尝试制作笔记应用程序时遇到上述错误,这是我的 kotlin 代码

主要活动


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
} 

注释列表

package com.example.notesapp

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.setFragmentResultListener
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton


class NotesList : Fragment() {

    
    val application= NotessApplication()
    private val noteViewModel: NoteViewModel by activityViewModels {


        NoteViewModelFactory(application.repository)
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_notes_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerview)
        val adapter = NotesListAdapter()
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(activity)

        noteViewModel.allNotes.observe(viewLifecycleOwner, Observer { notes ->
            // Update the cached copy of the words in the adapter.
            notes?.let { adapter.submitList(it) }
        })

        val fab = view.findViewById<FloatingActionButton>(R.id.fab)
        fab.setOnClickListener {

            view.findNavController().navigate(R.id.action_notesList_to_newNoteFragment)
            setFragmentResultListener("requestKey") { requestKey, bundle ->
                // We use a String here, but any type that can be put in a Bundle is supported
                val result = bundle.getString("bundleKey")
                onFragresult(result)
            }

        }

    }

    private fun onFragresult(result: String?) {
        if(result==null)
        {
            Toast.makeText(
                activity,
                R.string.empty_not_saved,
                Toast.LENGTH_LONG
            ).show()
        }
        else
        {
            val note = Note(result)
            noteViewModel.insert(note)
        }

    }


}

Application 类

package com.example.notesapp

import android.app.Application
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob

class NotessApplication : Application() {
    // Using by lazy so the database and the repository are only created when they're needed
    // rather than when the application starts

    val applicationScope = CoroutineScope(SupervisorJob())


    val database by lazy { NotesRoomDatabase.getDatabase(this,applicationScope) }
    val repository by lazy { NoteRepository(database.noteDao()) }
}

NOtesRoom数据库

package com.example.notesapp

import android.content.Context
import androidx.compose.ui.text.android.animation.SegmentType
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@Database(entities = arrayOf(Note::class),version = 1,exportSchema = false)
public abstract class NotesRoomDatabase : RoomDatabase(){

    abstract fun noteDao() : NotesDao



    private class NoteDatabaseCallback(
        private val scope: CoroutineScope
    ) : RoomDatabase.Callback() {

        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)
            INSTANCE?.let { database ->
                scope.launch {
                    populateDatabase(database.noteDao())
                }
            }
        }

        suspend fun populateDatabase(noteDao: NotesDao) {
            // Delete all content here.
            noteDao.deleteAll()

            // Add sample words.
            var word = Note("Hello")
            noteDao.insert(word)
            word = Note("World!")
            noteDao.insert(word)


        }
    }

    companion object{
        // Singleton prevents multiple instances of database opening at the
        // same time.

        @Volatile
        private var INSTANCE : NotesRoomDatabase?= null

        fun getDatabase(context: Context, scope: CoroutineScope) : NotesRoomDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database

            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    NotesRoomDatabase::class.java,
                    "note_database"
                ) .addCallback(NoteDatabaseCallback(scope))
                    .build()
                INSTANCE = instance
                // return instance
                instance
            }

        }

    }
}

还有 Mylogcat

2021-08-14 21:18:35.122 5115-5115/com.example.notesapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.notesapp, PID: 5115
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notesapp/com.example.notesapp.MainActivity}: android.view.InflateException: Binary XML file line #15: Binary XML file line #15: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: android.view.InflateException: Binary XML file line #15: Binary XML file line #15: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #15: Error inflating class fragment
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
        at com.example.notesapp.NotesRoomDatabase$Companion.getDatabase(NotesRoomDatabase.kt:60)
        at com.example.notesapp.NotessApplication$database$2.invoke(NotesApplication.kt:14)
        at com.example.notesapp.NotessApplication$database$2.invoke(NotesApplication.kt:14)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at com.example.notesapp.NotessApplication.getDatabase(NotesApplication.kt:14)
        at com.example.notesapp.NotessApplication$repository$2.invoke(NotesApplication.kt:15)
        at com.example.notesapp.NotessApplication$repository$2.invoke(NotesApplication.kt:15)
        at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
        at com.example.notesapp.NotessApplication.getRepository(NotesApplication.kt:15)
        at com.example.notesapp.NotesList$noteViewModel$2.invoke(NotesList.kt:25)
        at com.example.notesapp.NotesList$noteViewModel$2.invoke(NotesList.kt:22)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:52)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
        at com.example.notesapp.NotesList.getNoteViewModel(NotesList.kt:22)
        at com.example.notesapp.NotesList.onViewCreated(NotesList.kt:45)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:3065)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2988)
        at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:392)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:281)
        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:140)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
2021-08-14 21:18:35.126 5115-5115/com.example.notesapp E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        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 android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:699)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at com.example.notesapp.MainActivity.onCreate(MainActivity.kt:9)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

dao 和 entity 以及 rest 类都在那里,但我认为它们没有错误,但是如果需要,我也会添加它们,请帮忙

XML 代码

笔记列表

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".NotesList">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:listitem="@layout/recyclerview_item"
        android:padding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:contentDescription="Add Note"
        android:src="@drawable/ic_baseline_add_24"/>

    </androidx.constraintlayout.widget.ConstraintLayout>


</FrameLayout>

主要活动

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/myNavHostFragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:navGraph="@navigation/navigation"
    app:defaultNavHost="true" />

</androidx.constraintlayout.widget.ConstraintLayout>

Recycler 视图项目

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView"
        style="@style/note_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_light" />
</LinearLayout>
android 片段 nullpointerexception applicationcontext

评论

0赞 Omar Shawky 8/15/2021
它不能在第 15 行夸大 XML,因此 XML 可能是问题的原因,您可以发布 XML 代码吗?
3赞 CommonsWare 8/15/2021
删除。永远不要自己创建子类的实例(这同样适用于和)。val application= NotessApplication()ApplicationActivityService
0赞 Arsh Ansari 8/15/2021
我发布了xml引号,请查看它,如果不是那样,@CommonsWare如何从应用程序类访问存储库
0赞 CommonsWare 8/15/2021
那么,理想情况下,您将使用依赖反转系统(Dagger/Hilt、Koin 等)并将存储库注入到您的视图模型中。如果没有它,您的视图模型可能会扩展,因此它可以自行获取单例。AndroidViewModelApplication

答: 暂无答案