Search code examples
androidkotlinandroid-roomandroid-context

android.content.Context.getApplicationContext()' on a null object reference


I have this taskDataBase

@Database(
        entities = [
            Todo::class
        ],
        version = 1
)
abstract class TaskDataBase : RoomDatabase() {

    abstract val taskDao: TaskDao

    companion object {
        @Volatile
        private var INSTANCE: TaskDataBase? = null

        fun getInstance(context: Context): TaskDataBase {
            synchronized(this){
                return INSTANCE ?: Room.databaseBuilder(
                        context.applicationContext,
                        TaskDataBase::class.java,
                        "task_db"
                ).build().also {
                    INSTANCE = it
                }
            }
        }
    }
}

and the mainActivity is like this

class MainActivity : AppCompatActivity(), TodoAdapter.OnItemLongClickListener {
    private var todoList = mutableListOf(
            Todo("First Todo item", false),
            Todo("Second Todo item", true),
            Todo("Third Todo item", false),
            Todo("Forth Todo item", true),
            Todo("Fifth Todo item", false),
            Todo("Sixth Todo item", true),
            Todo("Seventh Todo item", false)
    )
    private val adapter = TodoAdapter(todoList, this)
    private val dao:TaskDao = TaskDataBase.getInstance(this).taskDao
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rvTodos.adapter = adapter
        rvTodos.layoutManager = LinearLayoutManager(this)

when i run the app i get this error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

it is telling me there is an error in the context. I don't know what to do. I tried to change but it didn't work out that much.


Solution

  • You are passing the context to the attribute before the context exists.

    You can assign the context after onCreate finishes.

    You can declare these attributes. Then you can set the values ​​after the setContentView.

    private var dao:TaskDao;
    
    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            dao = TaskDataBase.getInstance(this).taskDao
    }