nvt_dc
nvt_dc

Reputation: 125

Writing data to Firebase from a fragment in Android Studio

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.

Upvotes: 0

Views: 808

Answers (2)

MESADIEU Jeeffery
MESADIEU Jeeffery

Reputation: 11

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.

Upvotes: 1

Reaz Murshed
Reaz Murshed

Reputation: 24211

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());

Upvotes: 2

Related Questions