Make sure to call FirebaseApp.initializeApp(Context) first in Android

AndroidFirebase

Android Problem Overview


I am facing this issue and seen some answers on this site but did not get any proper solution.
I have used previous version of Firebase which works fine but when I try to upgrade using Upgradation and update Firebase class to DatabaseReference it shows error and not working.
I am adding my manifest file entire code so please help me to resolve this issue.
Here is my manifest

	<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="firebasechat.com.firebasechat">

	<uses-permission android:name="android.permission.INTERNET" />

	<application
		android:allowBackup="true"
		android:name=".Activity.SimpleBlog"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".Activity.RegisterActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />

				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	   
	</application>

</manifest>

my Module app is given below.

	apply plugin: 'com.android.application'

android {
	compileSdkVersion 26
	buildToolsVersion "26.0.0"
	defaultConfig {
		applicationId "firebasechat.com.firebasechat"
		minSdkVersion 15
		targetSdkVersion 26
		versionCode 1
		versionName "1.0"
		testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

		multiDexEnabled  true

	}
	buildTypes {
		release {
			minifyEnabled false
			proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
		}
	}
	packagingOptions {
		exclude 'META-INF/LICENSE'
		exclude 'META-INF/LICENSE-FIREBASE.txt'
		exclude 'META-INF/NOTICE'
	}
}



dependencies {
	compile fileTree(include: ['*.jar'], dir: 'libs')
	androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
		exclude group: 'com.android.support', module: 'support-annotations'
	})
	compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.volley:volley:1.0.0'
compile "com.google.firebase:firebase-database:11.0.0"
compile 'com.google.android.gms:play-services:11.0.0'
compile 'com.android.support:recyclerview-v7:25.0.0'
testCompile 'junit:junit:4.12'
	testCompile 'junit:junit:4.12'
}

and Project gradle

	// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
	repositories {
		jcenter()
	}
	dependencies {
		classpath 'com.android.tools.build:gradle:2.3.3'
		classpath 'com.google.gms:google-services:4.2.0'// Updated version of google service
	}
}
allprojects {
	repositories {
		jcenter()
		maven {
			url "https://maven.google.com" // Google's Maven repository
		}
	}
}
task clean(type: Delete) {
	delete rootProject.buildDir
}


Below is my Activity.

	public class RegisterActivity extends AppCompatActivity {

	EditText username, password;
	Button registerButton;
	String user, pass;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		username = (EditText)findViewById(R.id.username);
		password = (EditText)findViewById(R.id.password);
		registerButton = (Button)findViewById(R.id.registerButton);
	

          FirebaseApp.initializeApp(this);

	

		registerButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				user = username.getText().toString();
				pass = password.getText().toString();

			 
					final ProgressDialog pd = new ProgressDialog(RegisterActivity.this);
					pd.setMessage("Loading...");
					pd.show();

					String url = "https://pure-coda-174710.firebaseio.com/users.json";

					StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
						@Override
						public void onResponse(String s) {

//                            Firebase reference = new Firebase("https://pure-coda-174710.firebaseio.com/users");
							DatabaseReference reference = FirebaseDatabase.getInstance()
									.getReferenceFromUrl("https://pure-coda-174710.firebaseio.com/users");


							if(s.equals("null")) {
								reference.child(user).child("password").setValue(pass);
								Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_LONG).show();
							}
							else {
								try {
									JSONObject obj = new JSONObject(s);

									if (!obj.has(user)) {
										reference.child(user).child("password").setValue(pass);
										Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_LONG).show();
									} else {
										Toast.makeText(RegisterActivity.this, "username already exists", Toast.LENGTH_LONG).show();
									}

								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							pd.dismiss();
						}

					},new Response.ErrorListener(){
						@Override
						public void onErrorResponse(VolleyError volleyError) {
							System.out.println("" + volleyError );
							pd.dismiss();
						}
					});

					RequestQueue rQueue = Volley.newRequestQueue(RegisterActivity.this);
					rQueue.add(request);
				
			}
		});
	}
}

Android Solutions


Solution 1 - Android

In your SimpleBlog application class, initialize FirebaseApp in onCreate() method and remove it from RegisterActivity in order to have Firebase initialize into entire application, not just one Activity.

@Override
public void onCreate() {
    super.onCreate();
    FirebaseApp.initializeApp(this);
}

Also add apply plugin: 'com.google.gms.google-services' at the end of app gradle:

dependencies {
    ....
}

apply plugin: 'com.google.gms.google-services'

Plugin is required to process your json config from firebase and to avoid dependency collisions. You can read here for more details.

Solution 2 - Android

Spent literally a whole day. Finally, this was the solution.

Freaking 0 instead of 1 and you will not have to use the initialize firebaseapp or anything like that.

In Project gradle, use Google services: 4.0.0 and not 4.1.0.

Plus, apply plugin statement at the end is also not necessary in my experience.

(Hoping you have added firebase database from the tools => firebase assistant. Step 1 and step 2 are right and green. )

Solution 3 - Android

According to FirebaseApp documentation, you do not need to invoke this initialization, except that your app requires access to another Firebase project.

I invoked this initialization and sometime, user gets crash time to time when user opens my app, so I remove this line of code then everything works well. Be careful to invoke this initialization.

The capture of FirebaseApp documentation:

enter image description here

Update: below Exception will occur if you try to add this line [Some ads network requires this line, they also add some process in their AndroidManifest]

Failed to gain exclusive lock to the Firestore client's offline persistence. This generally means you are using Firestore from multiple processes in your app. Keep in mind that multi-process Android apps execute the code in your Application class in all processes, so you may need to avoid initializing Firestore in your Application class. If you are intentionally using Firestore from multiple processes, you can only enable offline persistence (i.e. call setPersistenceEnabled(true)) in one of them.

To fix it:

  1. add below method in your Application class:

    private boolean isMainProcess(Context context) { if (null == context) { return true; } ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

     int pid = android.os.Process.myPid();
     for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
         if (APPLICATION_ID.equals(processInfo.processName) && pid == processInfo.pid) {
             return true;
         }
     }
     return false;
    

    }

  2. Wrap onCreate of your Application

    @Override public void onCreate() { super.onCreate(); if (!isMainProcess(this)) { FirebaseApp.initializeApp(this); FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder() .setPersistenceEnabled(false) .build(); FirebaseFirestore.getInstance().setFirestoreSettings(settings); // other things return; } // other things }

UPDATE: Sometime, my app throws below exception

Unable to create application My Application Class : java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process MY_APPLICATION_ID. Make sure to call FirebaseApp.initializeApp(Context) first.

To Fix It: let update onCreate method:

@Override
public void onCreate() {
    super.onCreate();
    FirebaseApp.initializeApp(this);
    boolean isMain = isMainProcess(this);
    FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder().setPersistenceEnabled(isMain).build();
    FirebaseFirestore.getInstance().setFirestoreSettings(settings);
    if (!isMain) {
        // other things
        return;
    }
    // other things
}

Solution 4 - Android

Got same problem and solved this way:

in activity:

@Override
public void onCreate() {
    super.onCreate();
    FirebaseApp.initializeApp(this);
}

in app's gradle (at the end of file):

dependencies {
    ....
}

apply plugin: 'com.google.gms.google-services'

is project's gradle:

   dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.0.0'
}

Solution 5 - Android

  1. I had this same issue some time ago.

    You're trying to get an instance of Firebase without initialize it. Please add this line of code before you try to get an instance of Firebase:

    Just import latest version firebase and google play services.

    Recent update version (example):

add to these lines build.gradle

dependencies {

    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-core:16.0.7'
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'


}
apply plugin: 'com.google.gms.google-services'



dependencies {
    classpath 'com.android.tools.build:gradle:3.3.1'
    classpath 'com.google.gms:google-services:4.2.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

thats all. Enjoy your coding.

Solution 6 - Android

First thing first: Project config JSON's may go wrong/obsolete mostly on upgrade of Firebase.

Go to Tools->Firebase->Cloud Messaging->Set up firebase cloud messaging.

Even if you have done that in the past, it's worth the double check here as things get updated from time to time. I sync-ed my project and it solved the issue.

As for calling FirebaseApp.initializeApp, it is not necessary, at least not for FCM. See the FCM documentations.

Furthermore, if it return null it means that it fails, so calling it before calling getInstance won't do.

Note that this is the getInstance of FirebaseInstanceId:

public static FirebaseInstanceId getInstance() {
    return getInstance(FirebaseApp.getInstance());
}

Where on the other hand:

@Nullable
public static FirebaseApp initializeApp(Context var0) {
    Object var1 = sLock;
    synchronized(sLock) {
        if (zzf.containsKey("[DEFAULT]")) {
            return getInstance();
        } else {
            FirebaseOptions var2;
            return (var2 = FirebaseOptions.fromResource(var0)) == null ? null : initializeApp(var0, var2);
        }
    }
}

It means that it's if initializeApp returns null, you probably have issues with the configurations. At least - worth checking. To know where you are at, put a breakpoint at some point where Context is visible, and try to evaluate FirebaseApp.initialize(context) to make sure it does not return null.

Solution 7 - Android

Please downgrade google service plugin from version 4.1.0 to 4.0.1 in project's build.gradle

classpath 'com.google.gms:google-services:4.0.1'

And add this code to onCreate()

FirebaseApp.initializeApp(this);

it worked for me.

Solution 8 - Android

I had the same problem too and i noticed that this problem only occured to me when i added Firebase Storage dependency. So as i am using API 28, I made sure that all firebase dependencies have same import version i.e 16.0.5as of the storage dependency.

implementation 'com.google.firebase:firebase-core:16.0.5'
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'com.google.firebase:firebase-database:16.0.5'
implementation 'com.google.firebase:firebase-storage:16.0.5'

I updated my gradle version to

classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.2.0'

And i added the line below the app module

apply plugin: 'com.google.gms.google-services'

then it worked for me.

Solution 9 - Android

update the gradle main classpath 'com.google.gms:google-services:4.2.0'

Solution 10 - Android

No need to add anything in Application class or call initializeApp() for firebase. After adding firebase capabilities to your app through Tools -> Firebase - > (Any functionality) -> Make sure step 1 and 2 is green and checked.

Go to project gradle file and use classpath 'com.google.gms:google-services:4.2.0'

that's it.

Solution 11 - Android

To prevent this error, one need to follow all the steps involved in setting up Firebase for android https://firebase.google.com/docs/android/setup

I got the same error as I forgot to follow two steps and fixed it by

  1. adding classpath 'com.google.gms:google-services:4.2.0' to project level gradle build file.

  2. adding apply plugin: 'com.google.gms.google-services' to module level gradle build file.

Solution 12 - Android

I had the same problem , i Modified my Project build.gradle to be as follows

     dependencies {

    classpath 'com.android.tools.build:gradle:3.2.1'
    classpath 'com.google.gms:google-services:3.2.0'

....
                   }

then i added the line below into the app module

       apply plugin: 'com.google.gms.google-services'

and it was solved

Solution 13 - Android

I didn't use FirebaseApp.initializeApp(Context) on my project.

It works for me. You should check your gradle files and be sure you implemented this lines:

add apply plugin: 'com.google.gms.google-services' into your gradle(app)

or

add this classpath 'com.google.gms:google-services:4.2.0' into your gradle(project).

Solution 14 - Android

You are experiencing this error because of google updata, All you need is do the following

Change the following dependency from

dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:4.1.0'
    }

to

 dependencies {
            classpath 'com.android.tools.build:gradle:3.3.2'
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
            classpath 'com.google.gms:google-services:4.0.0'
        }

The difference is that google-services:4.1.0 should be changed to 4.0.0

Solution 15 - Android

implementation 'com.google.firebase:firebase-core:16.0.6

If error FirebaseApp.initializeApp(Context) add "mavenCentral" in your build.gradle

enter code here repositories {google() jcenter() mavenCentral() }

Solution 16 - Android

Try to downgrade or upgrade the Gradle version.

For example, your build.gradle have :

dependencies {
    classpath 'com.android.tools.build:gradle:3.3.0'
}

Change to

dependencies {
    classpath 'com.android.tools.build:gradle:3.2.0'
}

Solution 17 - Android

Try adding your app to firebase console and updating the new google-services.json file in your application. This worked for me, when I had tried to implement the app with the database and json file of another project.

Solution 18 - Android

After migration you have to update the dependencies to the new SDK, check this: https://stackoverflow.com/a/61681739/5279996

Solution 19 - Android

You are using very old method of firebase now you dont need to use

***FirebaseApp.initializeApp(context)*** 

remove this. then:

Just add Your App with package name to your firebase project download the google Json file from this link here add your package name and then copy the downloaded google json file in your “app” now Add

the instructed libraries into both app level and project level gradle. now just sync the

project and you are ready to use firebase.

Solution 20 - Android

When this error occurs, it's because you are not using the latest version of firebase dependencies.

Update all dependencies to the latest ones and you are good to go!

Solution 21 - Android

put these two lines in build.gradle ( app level )

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' 

enter image description here ( this picture taken from Firebase > Settings > Android App > Method of setting SDK

if it is correct , it will yeild error cannot find file 'google-services.json'

then you copy your google-service.json file that generated from Firebase > Setting > Android App > Click "google-services.json" to genetate the file.

You do not have to worry about the path that you will save this file. The error will show where do you need to save this file. For example I save in app/ ( next to build.gradle (app level ))

Solution 22 - Android

Using Kotlin,

> "Make sure to call FirebaseApp.initializeApp(Context) first in > Android"

this is an example for a correct Firebase Analytics initialization:

// declare_analytics
private lateinit var firebaseAnalytics: FirebaseAnalytics



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


        // Obtain the FirebaseAnalytics instance.
        firebaseAnalytics = Firebase.analytics


        val parameters = Bundle().apply {
            this.putString("level_name", "Jorgesys B. " + System.currentTimeMillis())
            this.putInt("level_difficulty", 10)
        }

        firebaseAnalytics.setDefaultEventParameters(parameters)


    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMohd Sakib SyedView Question on Stackoverflow
Solution 1 - AndroidFlorescu CătălinView Answer on Stackoverflow
Solution 2 - Androiduser3156040View Answer on Stackoverflow
Solution 3 - AndroidRobustView Answer on Stackoverflow
Solution 4 - Androidpw2View Answer on Stackoverflow
Solution 5 - AndroidmahendrenView Answer on Stackoverflow
Solution 6 - AndroidManeki NekoView Answer on Stackoverflow
Solution 7 - AndroidtariksuneView Answer on Stackoverflow
Solution 8 - AndroidLovish-PandeyView Answer on Stackoverflow
Solution 9 - AndroidBijeshView Answer on Stackoverflow
Solution 10 - AndroidandroidStudView Answer on Stackoverflow
Solution 11 - AndroidArnav RaoView Answer on Stackoverflow
Solution 12 - AndroidBrigth LigthView Answer on Stackoverflow
Solution 13 - AndroidmrshkView Answer on Stackoverflow
Solution 14 - Androidjava_majorView Answer on Stackoverflow
Solution 15 - AndroidCroidView Answer on Stackoverflow
Solution 16 - AndroidAgung PramonoView Answer on Stackoverflow
Solution 17 - AndroidYash Prashant NaikView Answer on Stackoverflow
Solution 18 - AndroidBraian CoronelView Answer on Stackoverflow
Solution 19 - AndroidSunil ChaudharyView Answer on Stackoverflow
Solution 20 - Androiduser14545206View Answer on Stackoverflow
Solution 21 - AndroidMooMooView Answer on Stackoverflow
Solution 22 - AndroidJorgesysView Answer on Stackoverflow