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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
nvt_dc
  • 133
  • 1
  • 9

1 Answers1

1

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());
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • Thanks for the help, I tried to use both the options but it didn't work! – nvt_dc Sep 29 '20 at 20:13
  • Strange! Do you see anything in the log saying initialization unsuccessful? If that's the case, you might consider checking this answer - https://stackoverflow.com/a/37901548/3145960 – Reaz Murshed Sep 29 '20 at 20:14
  • No. There's no log related to FirebaseInitProvider tag – nvt_dc Sep 29 '20 at 20:18
  • So, I figured it out that the issue was that I missed out to apply one plugin in Module level gradle file. – nvt_dc Oct 05 '20 at 14:19