Home » Android » android – how to properly initialize firebase app that can be used more than once?-Exceptionshub

android – how to properly initialize firebase app that can be used more than once?-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

usually I initialize firebase in my activity just like this

class MainActivity : AppCompatActivity() {


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

        // usually initializing firebase just like this
        FirebaseApp.initializeApp(this)

}

but now I need that firebaseApp to be passed to get FirebaseStorage instance like this:

    // set firebase option
    val optionBuilder = FirebaseOptions.Builder()
    optionBuilder.setStorageBucket("newBucket")
    val firebaseOption = optionBuilder.build()

    // initialize firebase app
    val app = FirebaseApp.initializeApp(this,firebaseOption)

    // create reference, pass app to firebase storage
    val storageRef = FirebaseStorage.getInstance(app).reference.child("profilePicture")

but the problem is…..

I need to create that firebase storage reference in more than one place. so how how to properly initialize firebase app so that I can use it in more than one place ?

do I need to initialize it in MainActivity AND recreate it again whenever I need to make storage reference ? it seems like a bad idea, but I don’t know …. please help 🙂

How to&Answers:

Just initialize it once and store it in a place where they can all access it – a singleton.