在Android中,请确保首先调用FirebaseApp.initializeApp(Context)函数

80
我遇到了这个问题,看到了这个网站上的一些答案,但没有得到任何解决方案。
我以前使用的 Firebase 版本运行良好,但当我尝试使用升级指南并更新 Firebase 类到 DatabaseReference 时,它显示错误并且无法工作。
我正在添加我的清单文件的整个代码,请帮助我解决这个问题。
这是我的 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>

以下是我的模块应用程序(Module app)

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

项目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
}

以下是我的 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);

            }
        });
    }
}

什么是错误? - Burhanuddin Rashid
@ Burhanuddin Rashid,这个错误发生在运行时,如下所示: java.lang.IllegalStateException: 在此进程中未初始化默认 FirebaseApp firebasechat.com.firebasechat。请确保首先调用 FirebaseApp.initializeApp(Context)。 - Mohd Sakib Syed
请展示您的清单文件、模块级别的 build.gradle 文件和项目级别的 build.gradle 文件代码。另外,您是否已经在项目中添加了 google-services.json 文件? - R.R.M
@R.R.M,我已经更新了我的问题,并添加了gradle文件,请检查并告诉我。 - Mohd Sakib Syed
2
你没有在模块级别的gradle文件底部添加这行代码吗:apply plugin: 'com.google.gms.google-services'? - R.R.M
当我没有包含我的Google项目应用程序ID时,我遇到了相同的错误。 - Rafael
22个回答

93
在你的SimpleBlog应用程序类中,在onCreate()方法中初始化FirebaseApp,并从RegisterActivity中移除它,以便Firebase能够更早地初始化。例如,一些Firebase附加服务在调用它们之前需要进行此初始化。
@Override
public void onCreate() {
    super.onCreate();
    FirebaseApp.initializeApp(this);
}

在app的gradle末尾添加apply plugin: 'com.google.gms.google-services'
dependencies {
    ....
}

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

插件是必需的,用于处理来自Firebase的JSON配置并避免依赖冲突。您可以阅读这里获取更多详细信息。

@ Florescu George Cătălin 感谢您的回答,我已经更新了我的问题,并添加了我的 Gradle 文件的全部代码。 - Mohd Sakib Syed
1
@SakibSyed 请尝试使用 classpath 'com.google.gms:google-services:3.0.0',而不是 classpath 'com.google.gms:google-services:3.1.0' - Cătălin Florescu
14
这个答案不应被接受,因为默认行为(据我所读)是不需要手动初始化Firebase应用程序。我自己尝试过这个方法,发现它不起作用。 - dinesharjani
1
对我来说不起作用,所以在您的项目gradle中,请使用Google服务:4.0.0而不是4.1.0,如下所述。 - Mohamed AbdelraZek
1
非常感谢!现在我的工作又可以顺利运行了! - Pedro Antonio Luque López
显示剩余5条评论

49

花了整整一天,最终找到了解决方案。

只需将 1 替换为 0,您就无需使用 initialize firebaseapp 或其他任何内容。

在项目 gradle 中,请使用 Google services:4.0.0 而不是 4.1.0

此外,根据我的经验,在结尾处应用插件声明也是不必要的。

(假设您已经从工具=> firebase助手中添加了firebase数据库。步骤 1 和步骤 2 是正确并且绿色的。)


5
感谢user3156040的建议,在项目Gradle中,请使用Google服务:4.0.0而不是4.1.0。这个变化对我有用。 - Nilesh
4
非常感谢,这个解决方案仍然有效。Android Studio默认生成的版本是4.1.0 :( 尽管有一个新版本4.2.0(它可以工作)。 - tosh17
4
使用 Firebase 已有 4 年,突然出现提示要调用 FirebaseApp.initializeApp(Context)。我只是将项目 gradle 中的 Google services 版本从 4.1.0 更改为 4.2.0,然后一切正常了! - Yo Apps
3
插件:com.google.gms.google-services是必需的!! 不要引诱人们涉及空内容!! 如果您不使用Firebase.initializeApp(context)调用,Firebase服务将通过对话框消息提醒您。从这里阅读文档:https://developers.google.com/android/guides/google-services-plugin - Cătălin Florescu
你能解释一下“Freaking 0 instead of 1”的意思吗?你在build.gradle里设置某个值为0了吗? - xaviersjs

25
根据FirebaseApp文档,除非您的应用程序需要访问另一个Firebase项目,否则不需要调用此初始化。
我调用了此初始化,有时用户打开我的应用程序会崩溃,所以我删除了这行代码,然后一切正常。请小心调用此初始化。
FirebaseApp文档摘录:

enter image description here

更新:如果您尝试添加此行[某些广告网络要求此行,它们还在其AndroidManifest中添加了一些进程],则会出现以下异常。

无法获得对Firestore客户端离线持久性的独占锁。这通常意味着您正在从应用程序的多个进程中使用Firestore。请注意,多进程Android应用程序在所有进程中执行您的Application类中的代码,因此您可能需要避免在Application类中初始化Firestore。如果您有意从多个进程中使用Firestore,则只能在其中一个进程中启用离线持久性(即调用setPersistenceEnabled(true))。

解决方法:

1)在您的Application类中添加以下方法:

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) 在你的Application中包装onCreate

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

更新:有时,我的应用程序会抛出以下异常

无法创建应用程序 My Application Class:java.lang.IllegalStateException: 在此进程中未初始化默认 FirebaseApp MY_APPLICATION_ID。请确保首先调用FirebaseApp.initializeApp(Context)。

修复方法:让我们更新onCreate方法:

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

这很好,但是可以用name.equals("")来替换StringUtils的使用。另外,在使用manager之前应该进行null检查! - IainCunningham

20
我遇到了同样的问题,并通过以下方法解决:

在活动中:

@Override
public void onCreate() {
    super.onCreate();
    FirebaseApp.initializeApp(this);
}
在应用程序的 Gradle 文件中(位于文件末尾):
dependencies {
    ....
}

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

这是项目的Gradle文件:

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

对我来说,在 apply plugin: 'com.android.application' 下方添加 apply plugin: 'com.google.gms.google-services' 是有效的。 - Nguyen Tan Dat
必须使用 com.google.gms:google-services:4.0.1 版本作为类路径,其他版本会出现错误,如果这个版本不适用于您,请尝试不同的版本。 - Olli
2
天啊,请不要这样做,Firebase 文档明确表示它不应该被显式地调用(除非你的应用程序中有多个 FS 实例),因为库会自动初始化它! - varun

11
  1. 我曾经遇到过同样的问题。

    你尝试获取Firebase的实例,但没有初始化它。 在尝试获取Firebase实例之前,请添加以下代码行:

    只需导入最新版本的Firebase和Google Play服务即可。

    最近的更新版本(示例):

将这些行添加到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
}

就这些了。享受编码的乐趣吧。


这确实行得通。我原来用的是4.1.0版本,改成4.2.0版本就不再出现以下错误了:“java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.allinlearning.assist_android. Make sure to call FirebaseApp.initializeApp(Context) first.” - Alyoshak

5

首先要注意的是:在 Firebase 升级时,项目配置 JSON 可能会出现错误/过时。

前往 工具->Firebase->云消息传递->设置 Firebase 云消息传递

即使您以前已经完成了这个步骤,也值得再次进行检查(点击此处),因为事情会不时地更新。我同步了我的项目并解决了问题。

关于调用 FirebaseApp.initializeApp,至少对于 FCM 来说,并不是必需的。请参阅FCM 文档

此外,如果它返回 null,则表示失败,因此在调用 getInstance 之前调用它不起作用。

请注意,这是 FirebaseInstanceId 的 getInstance:

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

另一方面,在哪里:

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

这意味着如果initializeApp返回null,则您可能存在配置问题。至少要检查一下。要知道您的位置,请在某个可见Context的地方设置断点,并尝试评估FirebaseApp.initialize(context)以确保它不会返回null

5
请在项目的 build.gradle 中将 Google 服务插件版本从 4.1.0 降级到 4.0.1。
classpath 'com.google.gms:google-services:4.0.1'

在onCreate()中添加以下代码:

FirebaseApp.initializeApp(this);

我尝试过,这个方法可行。


4
为了避免出现这个错误,需要按照设置 Firebase for Android 的所有步骤进行操作。详见:https://firebase.google.com/docs/android/setup 我之前也遇到过同样的错误,通过以下两个步骤解决:
1)在项目级别的 Gradle 构建文件中添加 classpath 'com.google.gms:google-services:4.2.0'
2)在模块级别的 Gradle 构建文件中添加 apply plugin: 'com.google.gms.google-services'

4

我也遇到了同样的问题,我注意到这个问题只发生在我添加Firebase Storage依赖项时。因此,由于我正在使用API 28,我确保所有Firebase依赖项都具有相同的导入版本,即存储依赖项的16.0.5

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'

我将Gradle版本更新到...
classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.2.0'

我在应用程序模块下添加了以下行:

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

然后对我来说它起作用了。


4.2.0版本已经修复了其中的一个漏洞。 - Maxwell

3

更新Gradle主类路径'com.google.gms:google-services:4.2.0'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接