Mohd Sakib Syed
Mohd Sakib Syed

Reputation: 1769

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

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

            }
        });
    }
}

Upvotes: 86

Views: 183472

Answers (22)

Cătălin Florescu
Cătălin Florescu

Reputation: 5148

In your SimpleBlog application class, initialize FirebaseApp in onCreate() method and remove it from RegisterActivity in order for Firebase to initialize more sooner. As example why sooner, some Firebase additional services require this initialization before calling them.

@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.

Upvotes: 97

java_major
java_major

Reputation: 21

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

Also you might be missing this plugin apply plugin: 'com.google.gms.google-services'

Upvotes: 2

Jorgesys
Jorgesys

Reputation: 126455

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)


    }

Upvotes: 0

MooMoo
MooMoo

Reputation: 1116

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

Upvotes: 0

user14545206
user14545206

Reputation:

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!

Upvotes: 0

Sunil Chaudhary
Sunil Chaudhary

Reputation: 1247

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.

Upvotes: 1

Braian Coronel
Braian Coronel

Reputation: 22867

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

Upvotes: 1

Robust
Robust

Reputation: 2485

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
}

Upvotes: 29

Yash Prashant Naik
Yash Prashant Naik

Reputation: 19

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.

Upvotes: 1

Arnav Rao
Arnav Rao

Reputation: 6992

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.

Upvotes: 4

kiliccambaz
kiliccambaz

Reputation: 69

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).

Upvotes: 3

tariksune
tariksune

Reputation: 77

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.

Upvotes: 5

Mahendren Mahisha
Mahendren Mahisha

Reputation: 1062

  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.

Upvotes: 11

androidStud
androidStud

Reputation: 532

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.

Upvotes: 3

Agung Pramono
Agung Pramono

Reputation: 439

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'
}

Upvotes: 1

Bijesh
Bijesh

Reputation: 347

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

Upvotes: 3

Croid
Croid

Reputation: 111

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

Upvotes: 1

user3156040
user3156040

Reputation: 751

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. )

Upvotes: 51

Lovish-Pandey
Lovish-Pandey

Reputation: 135

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.

Upvotes: 4

Brigth Ligth
Brigth Ligth

Reputation: 37

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

Upvotes: 2

Maneki Neko
Maneki Neko

Reputation: 1247

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.

Upvotes: 5

pw2
pw2

Reputation: 386

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'
}

Upvotes: 19

Related Questions