0

So, I have a fragment class and I am trying to write data to Firebase Realtime database using the below code in onCreateView() method,

databaseReference = FirebaseDatabase.getInstance().getReference("CollectionName"); String id = databaseReference.push().getKey(); databaseReference.child(id).setValue(new myModel(param1, param2)); 

After running this code, whenever I try to write data, I am getting below error:

Default FirebaseApp is not initialized in this process <package_name>. Make sure to call FirebaseApp.initializeApp(Context) first.

This error points to the line where I am trying to get the instance from the firebase.

Now, I've tried many things like using below statement in onCreate() method,

FirebaseApp.initializeApp(MainActivity.getContext()); 

Here, MainActivity is the class from where this fragment loads.

Also, I have all the necessary dependencies installed in both my Module level and Project level gradle files.

2 Answers 2

2

I think you could just initialize the Firebase in the onCreate function of your MainActivity using the following.

FirebaseApp.initializeApp(this); 

If you want to initialize it from your fragment, you could do this in the onCreateView before calling the FirebaseDatabase.getInstance().

FirebaseApp.initializeApp(getActivity()); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help, I tried to use both the options but it didn't work!
Strange! Do you see anything in the log saying initialization unsuccessful? If that's the case, you might consider checking this answer - stackoverflow.com/a/37901548/3145960
No. There's no log related to FirebaseInitProvider tag
So, I figured it out that the issue was that I missed out to apply one plugin in Module level gradle file.
1

Just open the built.gradle.kts (Module:app) file and add this line on the dependencies:

implementation("com.google.firebase:firebase-database:20.3.0") 

and then click on :synch now.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.