Java 如何解决 Android Firebase 错误“在此过程中未初始化默认 FirebaseApp”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40155941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:27:33  来源:igfitidea点击:

How can I solve the Android Firebase error "Default FirebaseApp is not initialised in this process"?

javaandroidfirebasefirebase-realtime-databasefirebase-authentication

提问by Subham Kaps

I am using FirebaseAuth for user registration with email and password, and I have already added the plugin and dependencies in my project.

我正在使用 FirebaseAuth 通过电子邮件和密码进行用户注册,并且我已经在我的项目中添加了插件和依赖项。

MainActivity.java

主活动.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText ed_email, ed_pass;
Button but_login;
ProgressDialog progressDialog;
FirebaseAuth firebaseAuth;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context=getApplicationContext();
    FirebaseApp.initializeApp(context);
    firebaseAuth=FirebaseAuth.getInstance();

    ed_email= (EditText) findViewById(R.id.ed_email);
    ed_pass= (EditText) findViewById(R.id.ed_pass);
    but_login= (Button) findViewById(R.id.but_login);
    but_login.setOnClickListener(this);
    progressDialog=new ProgressDialog(this);
}
public void registerUser(){
    String email=ed_email.getText().toString().trim();
    String pass=ed_pass.getText().toString().trim();
    if(TextUtils.isEmpty(email)){
        Toast.makeText(getApplicationContext(),"Invalid Input",Toast.LENGTH_SHORT).show();
        return;
    }
    if(TextUtils.isEmpty(pass)){
        Toast.makeText(getApplicationContext(),"Invalid Input",Toast.LENGTH_SHORT).show();
        return;
    }
    progressDialog.setMessage("You are registering...");
    progressDialog.show();
    firebaseAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
                progressDialog.hide();
            } else {
                Toast.makeText(getApplicationContext(), "Sorry...!!!", Toast.LENGTH_SHORT).show();
                progressDialog.hide();
            }
        }

    });


}

@Override
public void onClick(View v) {
    registerUser();
}

}

}

logcat -

logcat -

com.skapsdevelopment.firebase E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.skapsdevelopment.firebase, PID: 31993
Theme: themes:{default=overlay:com.resurrectionremix.pitchblack, iconPack:com.baranovgroup.nstyle, fontPkg:com.resurrectionremix.pitchblack, com.android.systemui=overlay:com.resurrectionremix.pitchblack, com.android.systemui.navbar=overlay:com.resurrectionremix.pitchblack}
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skapsdevelopment.firebase/com.skapsdevelopment.firebase.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.skapsdevelopment.firebase. Make sure to call FirebaseApp.initializeApp(Context) first.
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5461)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.skapsdevelopment.firebase. Make sure to call FirebaseApp.initializeApp(Context) first.
   at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
   at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
   at com.skapsdevelopment.firebase.MainActivity.onCreate(MainActivity.java:35)
   at android.app.Activity.performCreate(Activity.java:6251)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)?
   at android.app.ActivityThread.-wrap11(ActivityThread.java)?
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)?
   at android.os.Handler.dispatchMessage(Handler.java:102)?
   at android.os.Looper.loop(Looper.java:148)?
   at android.app.ActivityThread.main(ActivityThread.java:5461)?
   at java.lang.reflect.Method.invoke(Native Method)?
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)?
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)?

My App is not starting and showing the following error:

我的应用程序未启动并显示以下错误:

java.lang.IllegalStateException: Default FirebaseApp is not initialized in this 
process com.skapsdevelopment.firebase. 
Make sure to call FirebaseApp.initializeApp(Context) first.

Why is the app not starting properly?

为什么应用程序无法正常启动?

回答by Orab?g

It's stated in the Docsthat the FirebaseApp.initializeApp() should be called from the Application.

它在声明文件的FirebaseApp.initializeApp()应该从应用程序中调用。

Did you try to create and Application instance (if you don't have one already), and call FirebaseApp.initializeApp(this)from its onCreate() method ?

您是否尝试创建 Application 实例(如果您还没有),并FirebaseApp.initializeApp(this)从其 onCreate() 方法调用?

回答by Lean Vitale

You need to add initializeAppin your program. I can show you how it's done.

您需要在程序中添加initializeApp。我可以告诉你它是如何完成的。

First create a new class and extend Application.

首先创建一个新类并扩展Application

public class SimpleBlog extends Application {

@Override
public void onCreate() {
    super.onCreate();
    if(!FirebaseApp.getApps(this).isEmpty()) {
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }
}

Lastly, go to Manifest and add in the application like this:

最后,转到 Manifest 并像这样添加应用程序:

<application
    android:name=".SimpleBlog"  <------
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

And this is all...

而这一切……

回答by george mano

Double-check the following as this has worked for me:

仔细检查以下内容,因为这对我有用:

Added in your project level gradle file:

在您的项目级 gradle 文件中添加:

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

And on your app-build gradle file:

在你的 app-build gradle 文件中:

apply plugin: 'com.android.application'

android {
  // ...
}

dependencies {
  // ...
  compile 'com.google.firebase:firebase-core:10.0.1'

  // Getting a "Could not find" error? Make sure you have
  // the latest Google Repository in the Android SDK manager
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services' 

Link

关联

回答by Darush

In my case Proguard was causing the problem so this is what I did: - If there is any class in the AndroidManifest.xml with "YourClass"or ".YourClass", change it to its full package name: "com.yourpackage.yourClass"

在我的情况下,Proguard 导致了问题,所以这就是我所做的: - 如果 AndroidManifest.xml 中有任何带有"YourClass"或 的类".YourClass",请将其更改为其完整的包名称:"com.yourpackage.yourClass"

回答by Gene Bo

Thanks to the answers here, I went through the check list of possible issues when I encountered this error.

感谢这里的答案,当我遇到此错误时,我查看了可能存在的问题的检查列表。

Finally I realized .. I had started a new module in Android Studio, with a different package name than what's already registered on the Firebase Console for the Firebase instance I had set up. Simple mistake - I forgot to add the new package name to the Console config.

最后我意识到.. 我在 Android Studio 中启动了一个新模块,它的包名与我在 Firebase 控制台上为我设置的 Firebase 实例注册的包名不同。一个简单的错误 - 我忘记将新的包名称添加到控制台配置中。

After I got this right, it started to work. Remembering all the little details expected by Firebase Console can be tricky sometimes.. gotta be alert/"config-cognizant"there for sure

在我做对了之后,它开始工作了。记住 Firebase 控制台所期望的所有小细节有时可能会很棘手.. 一定要警惕/ “配置认知”在那里

回答by rsssssonsss

I also faced the above issue. I downloaded all plugins and checked for updates with NuGet. In the end, I found the crashing was due to the Application Package Namenot matching the one assigned in Google Dev.

我也遇到了上面的问题。我下载了所有插件并使用 NuGet 检查了更新。最后,我发现崩溃是由于应用程序包名称与 Google Dev 中分配的名称不匹配。

  • Make sure that your google-services.json is assigned a build action of GoogleServicesJson

  • Check that your application package name matches the one that you assigned in the Google Dev Console

  • 确保为您的 google-services.json 分配了 GoogleServicesJson 的构建操作

  • 检查您的应用程序包名称是否与您在 Google Dev Console 中指定的名称匹配

回答by Dhruvisha

First thing Make sure you register your application in the Firebase Consoleand you have added the google-services.jsonfile in the app.

第一件事确保您在Firebase 控制台中注册了您的应用程序,并且您已在应用程序中添加了google-services.json文件。

Second Check the whether you have add all the dependencyor not. Add following dependency in the App-bulid Gradlefile:-

其次检查您是否添加了所有依赖项。在App-bulid Gradle文件中添加以下依赖项:-

buildscript {

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.google.gms:google-services:4.0.0'
    }

And add in project level bulid gradlefile:-

并添加项目级别的 bulid gradle文件:-

dependencies
 {
     implementation 'com.google.firebase:firebase-core:16.0.1'
     implementation 'com.google.firebase:firebase-auth:16.0.2'
 } 
 apply plugin: 'com.google.gms.google-services'    

回答by murtaza agaz

Follow these steps:

按着这些次序:

  1. Remove FirebaseApp.initializeApp(context);as you do not need it in the newer versions of Firebase
  2. Add your app with package name to your Firebase project. Download the Google JSON file with your package name and add the downloaded file to your app
  3. Add the instructed libraries into both app level and project level gradle
  4. Sync the project and you are ready to use Firebase
  1. 删除,FirebaseApp.initializeApp(context);因为您在较新版本的 Firebase 中不需要它
  2. 将带有包名称的应用添加到 Firebase 项目中。使用您的包名称下载 Google JSON 文件并将下载的文件添加到您的应用程序
  3. 将指示的库添加到应用程序级别和项目级别的 gradle 中
  4. 同步项目,您就可以使用 Firebase

For further info see the Firebase Authentication Guide.

有关更多信息,请参阅Firebase 身份验证指南

回答by manish kumar sah

please add this classpath 'com.google.gms:google-services:4.0.1' at the place of classpath 'com.google.gms:google-services:4.1.0'

请在类路径“com.google.gms:google-services:4.1.0”的位置添加此类路径“com.google.gms:google-services:4.0.1”

回答by Zia

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

在项目的 build.gradle 中将 google 服务插件从 4.1.0 版降级到 4.0.1 版

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