Q: 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.

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

