Home > database >  Kotlin singleton with object issue
Kotlin singleton with object issue

Time:09-23

I am trying to do the singleton pattern with Kotlin and I'm not understanding why I am getting null pointer exception here

object AppController : Application() {
    private val queue: RequestQueue = Volley.newRequestQueue(applicationContext)

   fun getRequestQueue(): RequestQueue {
        return queue
    }
}

In my main activity I am calling:

private val controller  = AppController
private val queue = AppController.getRequestQueue()

Ay help is appreciated. Sorry. I am not sure why code isn't formatting properly.

CodePudding user response:

Simply change object into class, probably android has problem to initialize it

class AppController : Application() {
    private val queue: RequestQueue = Volley.newRequestQueue(applicationContext)

   fun getRequestQueue(): RequestQueue {
        return queue
    }
}

Cheers

CodePudding user response:

You didn't specify which line of code throws the exception, so I would assume it's this one:

private val queue: RequestQueue = Volley.newRequestQueue(applicationContext)

Although I can't see this mentioned in the documentation, I wouldn't expect applicationContext to be available before your Application's onCreate is called, and by declaring the property in such a way you're invoking applicationContext during the constructor call, before onCreate. I'd suggest implementing the following change:

object AppController : Application() {
    private lateinit var queue: RequestQueue

    override fun onCreate() {
        super.onCreate()
        queue = Volley.newRequestQueue(applicationContext)
    }


   fun getRequestQueue(): RequestQueue {
        return queue
    }
}

This should ensure applicationContext is initialized at the time you're accessing it.

  • Related