mark
mark

Reputation: 105

I'm getting a NullPointerException when trying to use a room database

I'm currently trying to use a room database in my app for the first time. My code is supposed to save journal entries to a database when the user adds them, and load the entries into a recyclerview when the app opens. However, I keep getting this error when I open my app:

2020-11-25 12:12:56.326 15563-15563/com.google.gradient.red E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.google.gradient.red, PID: 15563
    java.lang.NullPointerException
        at com.google.gradient.red.database.JournalDatabase$Companion.getDatabase(JournalDatabase.kt:23)
        at com.google.gradient.red.ui.home.HomeFragment$onViewCreated$1.invokeSuspend(HomeFragment.kt:42)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Here is my code:

package com.google.gradient.red.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.google.gradient.red.dao.JournalDao
import com.google.gradient.red.entities.Journal

@Database(entities = [Journal::class], version = 1, exportSchema = false)
abstract class JournalDatabase: RoomDatabase() {

    companion object{
        var journalDatabase: JournalDatabase? = null

        @Synchronized
        fun getDatabase(context: Context): JournalDatabase{
            if (journalDatabase != null) {
                journalDatabase = Room.databaseBuilder(context,
                JournalDatabase::class.java,
                "journal.db").build()
            }
            return journalDatabase!!
        }
    }

    abstract fun JournalDao():JournalDao

}

Does anyone know what my error means? I think that it's saying that there isn't a database existing there, but I don't know how I could actually solve my issue.

This is my first time using room and I've been trying to figure this out for a while, so any help would be greatly appreciated!

Upvotes: 2

Views: 1418

Answers (1)

StuStirling
StuStirling

Reputation: 16181

Your if condition is wrong. It should be

if (journalDatabase == null) {
    journalDatabase = Room.databaseBuilder(context,
    JournalDatabase::class.java,
    "journal.db").build()
}
return journalDatabase!!   

Upvotes: 1

Related Questions