繁体   English   中英

确保先在 Android 中调用 FirebaseApp.initializeApp(Context)

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

我正面临这个问题,并在此站点上看到了一些答案,但没有得到任何适当的解决方案。
我使用了以前版本的Firebase ,它运行良好,但是当我尝试使用Upgradation进行升级并将Firebase class 更新到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'
}

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
}

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

            }
        });
    }
}

在您的SimpleBlog应用程序类中,在onCreate()方法中初始化 FirebaseApp 并将其从RegisterActivity中删除,以便将 Firebase 初始化为整个应用程序,而不仅仅是一个 Activity。

@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 配置并避免依赖冲突。 您可以阅读此处了解更多详情。

花了一整天的时间。 最后,这就是解决方案。

使用 0 而不是 1,您将不必使用 initialize firebaseapp 或类似的东西。

在 Project gradle 中,使用 Google 服务: 4.0.0 而不是 4.1.0。

另外,根据我的经验,最后的 apply plugin 语句也不是必需的。

(希望你已经从工具中添加了 firebase 数据库 => firebase 助手。第 1 步和第 2 步是正确的和绿色的。)

根据FirebaseApp文档,您不需要调用此初始化,除非您的应用需要访问另一个 Firebase 项目。

我调用了这个初始化,有时,当用户打开我的应用程序时,用户会不时崩溃,所以我删除了这行代码,然后一切正常。 小心调用这个初始化

FirebaseApp 文档的捕获:

在此处输入图片说明

更新:如果您尝试添加此行,则会发生以下异常 [某些广告网络需要此行,他们还在其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)裹onCreate您的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
}

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

无法创建应用程序我的应用程序类: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
}

遇到同样的问题并以这种方式解决:

在活动中:

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

仅此而已。 享受你的编码。

首先第一件事:项目配置 JSON 可能会出错/过时,主要是在 Firebase 升级时。

转到Tools->Firebase->Cloud Messaging->Set up firebase cloud messages

即使您过去这样做过,也值得在这里仔细检查因为事情会不时更新。 我同步了我的项目,它解决了这个问题。

至于调用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。

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

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

并将此代码添加到 onCreate()

FirebaseApp.initializeApp(this);

它对我有用。

我也遇到了同样的问题,我注意到这个问题只有在我添加 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'

然后它对我有用。

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

无需在 Application 类中添加任何内容或为 firebase 调用 initializeApp()。 通过工具 -> Firebase ->(任何功能) -> 确保第 1 步和第 2 步为绿色并选中,向您的应用添加 Firebase 功能后。

转到项目 gradle 文件并使用classpath 'com.google.gms:google-services:4.2.0'

就是这样。

为防止出现此错误,需要遵循为 Android https://firebase.google.com/docs/android/setup设置 Firebase 所涉及的所有步骤

我遇到了同样的错误,因为我忘记执行两个步骤并通过以下方式修复它

1) 将类路径 'com.google.gms:google-services:4.2.0' 添加到项目级 gradle 构建文件。

2) 将apply plugin: 'com.google.gms.google-services' 添加到模块级 gradle 构建文件。

我有同样的问题,我修改了我的项目 build.gradle 如下

     dependencies {

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

....
                   }

然后我将下面的行添加到应用程序模块中

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

它解决了

我没有在我的项目中使用FirebaseApp.initializeApp(Context)

它对我有用。 您应该检查您的 gradle 文件并确保您实现了以下几行:

apply plugin: 'com.google.gms.google-services'到您的 gradle(app) 中

将此类classpath 'com.google.gms:google-services:4.2.0'到您的 gradle(项目)中。

由于谷歌更新,您遇到此错误,您只需要执行以下操作

更改以下依赖项

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

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

不同的是 google-services:4.1.0 应该改为 4.0.0

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

如果错误 FirebaseApp.initializeApp(Context) 在 build.gradle 中添加“mavenCentral”

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

尝试降级或升级 Gradle 版本。

例如,你的 build.gradle 有:

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

更改为

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

尝试将您的应用添加到 Firebase 控制台并更新应用中的新 google-services.json 文件。 当我尝试使用另一个项目的数据库和 json 文件来实现该应用程序时,这对我有用。

迁移后,您必须将依赖项更新到新 SDK,请检​​查: https : //stackoverflow.com/a/61681739/5279996

您现在使用的是非常旧的 firebase 方法,现在您不需要使用

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

删除这个。 然后:

只有包名从这个链接您的应用添加到您的火力点项目下载谷歌的JSON文件在这里添加您的包名称,然后在你的“应用程序”下载的谷歌JSON文件复制现在加入

指示库进入应用程序级别和项目级别的 gradle。 现在只需同步

项目,您已准备好使用 firebase。

发生此错误时,是因为您没有使用最新版本的 firebase 依赖项。

将所有依赖项更新为最新的,一切顺利!

将这两行放在 build.gradle (应用程序级别)

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

在此处输入图片说明 (这张图片取自 Firebase > Settings > Android App > Method of setting SDK

如果正确,则会出现错误找不到文件“google-services.json”

然后复制从 Firebase > 设置 > Android 应用程序生成的 google-service.json 文件 > 单击“google-services.json”以生成文件。

您不必担心保存此文件的路径。 该错误将显示您需要在哪里保存此文件。 例如我保存在 app/ (旁边 build.gradle (应用程序级别))

使用 Kotlin,

“确保首先在 Android 中调用 FirebaseApp.initializeApp(Context)”

这是正确 Firebase Analytics 初始化的示例:

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


    }

对我来说,我添加了

plugins {
    id 'com.google.gms.google-services'
}

在应用程序级别下的 build.gradle 文件中

由于Google服务和Firebase身份验证更新而导致此错误

只需更新它们。

只是这个

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

对此

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

将来寻求更好,更快速的解决方案

这是您可以同时更新firebase-auth和google-service的方法

在使用firebase的类的oncreate中使用它。

FirebaseApp.initializeApp(Context); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM