1

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.

1
  • The code snippets you added are not visible , I can only see "..." on them, can you update your post and make sure the code is visible on the preview? Commented Sep 22, 2021 at 15:55

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for suggestion, but I want to limit instances of this, so class doesn't work for me.
@JoeBones Instance of the application is automatically created by the system if you refer to the class in the AndroidManifest, this cannot be an Object, the official document mentions how the app class is used. Please see - developer.android.com/guide/topics/manifest/…
0

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.

1 Comment

Well, that didn't work, but your suggestion led to a solution. I needed to pass a reference of the Context from my calling activity. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.