78

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

            }
        });
    }
}
Ashish
  • 6,791
  • 3
  • 26
  • 48
Mohd Sakib Syed
  • 1,679
  • 1
  • 25
  • 42
  • What is the error ? – Burhanuddin Rashid Aug 31 '17 at 09:28
  • @ Burhanuddin Rashid this error occurs on run time like java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process firebasechat.com.firebasechat. Make sure to call FirebaseApp.initializeApp(Context) first. – Mohd Sakib Syed Aug 31 '17 at 09:31
  • Please show your manifest, module level build.gradle and project level build.gradle file code. And also have you added google-services.json file in your project? – R.R.M Aug 31 '17 at 10:00
  • @R.R.M I have update my question by adding `gradle file` so kindly check it and let me know. – Mohd Sakib Syed Aug 31 '17 at 10:15
  • 2
    Haven't you added this line to the bottom of your module level gradle fille : apply plugin: 'com.google.gms.google-services' ? – R.R.M Aug 31 '17 at 10:21
  • I got same error when I didn't include my Google project app id – Rafael Jul 18 '18 at 05:00

22 Answers22

91

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.

Cătălin Florescu
  • 5,012
  • 1
  • 25
  • 36
  • Did you added configuration in gradle files? – Cătălin Florescu Aug 31 '17 at 09:49
  • @ Florescu George Cătălin Thanks for answer , I have update my question in which I have added entire code of my gradle files. – Mohd Sakib Syed Aug 31 '17 at 10:07
  • I have added plugin but build not get generate and shows error like below ***Error:Execution failed for task ':app:processDebugGoogleServices'. > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 11.0.4.*** – Mohd Sakib Syed Aug 31 '17 at 11:03
  • 1
    @SakibSyed try using `classpath 'com.google.gms:google-services:3.0.0'`, not `classpath 'com.google.gms:google-services:3.1.0'` – Cătălin Florescu Aug 31 '17 at 11:09
  • @ Florescu George Thanks you so much for help me and you have resolved my issue. Thank you so much – Mohd Sakib Syed Aug 31 '17 at 11:41
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153356/discussion-between-sakib-syed-and-florescu-george-ctlin). – Mohd Sakib Syed Aug 31 '17 at 11:45
  • In your root build.gradle add classpath 'com.google.gms:google-services:3.1.0' inside dependency – Pradeep Kumar Kushwaha Jun 05 '18 at 12:45
  • 13
    This should NOT be the accepted answer, since default behavior (from what I'm reading) is that initializing "by hand" Firebase app is not necessary. I myself have tried this and found that it doesn't work. – dinesharjani Jun 23 '18 at 16:39
  • 1
    Doesn't work for me so as mentioned below In your Project gradle, use Google services: 4.0.0 instead of 4.1.0 – Mohamed AbdelraZek Mar 17 '19 at 23:08
  • 1
    Thank you so much! Now my work run smoothly again! – Pedro Antonio Luque López Mar 16 '21 at 20:53
49

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

user3156040
  • 723
  • 5
  • 5
  • 5
    Thanks user3156040, "In Project gradle, use Google services: 4.0.0 and not 4.1.0" This change worked for me. – Nilesh Feb 18 '19 at 08:14
  • 4
    Many thanks, this solution still actually. Android studio by default generated 4.1.0 :( although there is a new version 4.2.0(it works) – tosh17 Mar 05 '19 at 09:21
  • 3
    After 4 years of using Firebase, it suddenly says call FirebaseApp.initializeApp(Context) .... I just changed the Project gradle, from Google services: 4.1.0 to >>> 4.2.0.... and eveyting worked fine! – Yo Apps Mar 19 '19 at 14:07
  • 3
    Plugin: `com.google.gms.google-services` is necessary !! Don't induce people in null things !! Firebase service will notice you if you don't call `Firebase.initializeApp(context)` with a dialog message. Read the documentation from here: https://developers.google.com/android/guides/google-services-plugin – Cătălin Florescu Apr 17 '19 at 13:20
  • Can you explain what you mean by "Freaking 0 instead of 1". Are you setting some value to 0 in your build.gradle? – xaviersjs Feb 17 '21 at 21:57
25

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
}
Robust
  • 2,415
  • 2
  • 22
  • 37
  • This is nice, but use of StringUtils may be replaced by name.equals(""). Also, manager should be null-checked before using it! – IainCunningham Sep 25 '18 at 20:38
20

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'
}
pw2
  • 326
  • 2
  • 8
  • For me, apply plugin: 'com.google.gms.google-services' is added at top right following apply plugin: 'com.android.application' works. – Nguyen Tan Dat Dec 12 '18 at 08:28
  • Had to use `com.google.gms:google-services:4.0.1` version as classpath, got errors with some other versions, so keep trying different versions if this doesn't work for you – Olli Feb 14 '19 at 13:34
  • 2
    OMG please don't do this, the firebase documentation literally says it must not be called explicitly (unless you have more than one FS instance in your app) as the library auto-initializes it! – varun Apr 27 '19 at 20:26
11
  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.

Bennik2000
  • 1,112
  • 11
  • 25
Mahendren Mahisha
  • 1,072
  • 11
  • 9
  • This indeed works. I was using 4.1.0 and changing to 4.2.0 was all it took to stop getting this: "java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.allinlearning.assist_android. Make sure to call FirebaseApp.initializeApp(Context) first." – Alyoshak Mar 19 '19 at 20:42
5

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.

Maneki Neko
  • 1,177
  • 1
  • 14
  • 24
5

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.

tariksune
  • 79
  • 1
  • 7
4

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.

Lovish-Pandey
  • 135
  • 1
  • 15
4

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.

Arnav Rao
  • 6,692
  • 2
  • 34
  • 31
3

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

Bijesh
  • 317
  • 3
  • 11
3

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.

androidStud
  • 532
  • 4
  • 9
3

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

2

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

2

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'

shareef
  • 9,255
  • 13
  • 58
  • 89
java_major
  • 21
  • 3
1
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() }
Croid
  • 111
  • 5
1

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'
}
Agung Pramono
  • 429
  • 4
  • 7
1

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.

1

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

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
0

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.

Sunil Chaudhary
  • 1,221
  • 12
  • 25
0

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!

0

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

MooMoo
  • 1,086
  • 12
  • 22
0

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)


    }
Jorgesys
  • 124,308
  • 23
  • 334
  • 268