首页 > 解决方案 > java.lang.RuntimeException: Unable to start activity ComponentInfo 确保首先调用 FirebaseApp.initializeApp(Context)

问题描述

看到很多,但没有运气,直到我阅读了在 Android 上控制你的 Firebase Init

因此,当我添加提到的代码块时,当我单击登录或注册时,我的应用程序不会持续崩溃。

添加到 RegistrationActivity.java 时不会崩溃

FirebaseOptions.Builder builder = new FirebaseOptions.Builder()
   .setApplicationId("1:0123456789012:android:0123456789abcdef")
   .setApiKey("your_api_key")
   .setDatabaseUrl("https://your-app.firebaseio.com")
   .setStorageBucket("your-app.appspot.com");
FirebaseApp.initializeApp(this, builder.build());

输入我的 Firebase 用户后我无法登录,但那是因为我从未从提供给我的 DB 值的示例值中填写我的 Firebase 值。但是我很困惑为什么我的应用程序不会立即与我的 RegistrationActivity.Java 的这段代码一起崩溃,但是当我将其注释掉时,我得到了标题中提到的错误。

有人可以解释一下我如何在没有上面代码块的情况下让我的原始代码工作,还是这是新方法?当我开始弄乱我的 Gradle 文件时,我的问题就开始了,所以这就是我今天所处的位置。TIA。

这是我的项目 Gradle

buildscript {

ext.versions = [
        'compileSdk'    : 27,
        'targetSdk'     : 27,
        'buildTools'    : '27.0.3',
//            'butterknife'   : '8.8.1',
//            'glide'         : '4.6.1',
//            'kotlin'        : '1.2.21',
//            'retrofit'      : '2.3.0',
//            'supportLibrary': '27.0.2'
]

repositories {
    google()
    jcenter()
}

dependencies {
    classpath 'com.android.tools.build:gradle:3.1.2'
    classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.5.4'
    //classpath 'com.google.gms:google-services:3.1.0'
}
allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }// Google's Maven repository
    }
}
}

这是我的 Module App Gradle 应用插件:'com.android.application'

android {
compileSdkVersion versions.compileSdk
buildToolsVersion versions.buildTools

defaultConfig {
    applicationId "com.example.tinder"
    minSdkVersion 26
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner 
"android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-
optimize.txt'), 'proguard-rules.pro'
    }
    customDebug {
        debuggable true
    }
}

}

repositories {
google()
jcenter()
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:support-annotations:27.1.1'

implementation 'com.google.firebase:firebase-core:15.0.2'
implementation 'com.google.firebase:firebase-auth:15.1.0'
implementation 'com.google.firebase:firebase-storage:15.0.2'
implementation 'com.google.firebase:firebase-database:15.0.1'

implementation 'com.github.bumptech.glide:glide:4.7.1'
implementation 'com.lorentzos.swipecards:library:1.0.9'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'

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

这是我的 RegistrationActivity.java 包 com.example.tinder;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class RegistrationActivity extends AppCompatActivity {
private Button mRegister;
private EditText mEmail, mPassword, mName;
private RadioGroup mRadioGroup;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);

//
//        FirebaseOptions.Builder builder = new FirebaseOptions.Builder()
//                            

 //  .setApplicationId("1:0123456789012:android:0123456789abcdef")
//                .setApiKey("your_api_key")
//                .setDatabaseUrl("https://your-app.firebaseio.com")
//                .setStorageBucket("your-app.appspot.com");
//        FirebaseApp.initializeApp(this, builder.build());

    mAuth = FirebaseAuth.getInstance();
    firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser user =     
FirebaseAuth.getInstance().getCurrentUser();
            if (user != null) {
                Intent intent = new Intent(RegistrationActivity.this, 
MainActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }
    };

    mRegister = (Button) findViewById(R.id.register);

    mEmail = (EditText) findViewById(R.id.email);
    mPassword = (EditText) findViewById(R.id.password);
    mName = (EditText) findViewById(R.id.name);
    mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);


    mRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            int selectId = mRadioGroup.getCheckedRadioButtonId();
            final RadioButton radioButton = (RadioButton) 
findViewById(selectId);
            if(radioButton.getText() == null){
                return;
            }

            final String email = mEmail.getText().toString();
            final String password = mPassword.getText().toString();
            final String name = mName.getText().toString();
            mAuth.createUserWithEmailAndPassword(email, 
 password).addOnCompleteListener(RegistrationActivity.this, new 
 OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        Toast.makeText(RegistrationActivity.this, "sign up 
 error", Toast.LENGTH_SHORT).show();
                    }else{
                        String userId = mAuth.getCurrentUser().getUid();

                        DatabaseReference currentUserDb = 
 FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
                        Map userInfo = new HashMap<>();
                        userInfo.put("name" , name);
                        userInfo.put("gender", 
 "Male");//radioButton.getTag().toString());
                        userInfo.put("profileImageUrl", "default");
                        currentUserDb.updateChildren(userInfo);
                    }
                }
            });
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(firebaseAuthStateListener);

}

@Override
protected void onStop() {
    super.onStop();
    mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
}

这是我的 MainActivitiy.java

package com.example.tinder;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
   import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
   import android.widget.ListView;
    import android.widget.Toast;

   import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;
    import com.google.firebase.database.ChildEventListener;
    import com.google.firebase.database.DataSnapshot;
    import com.google.firebase.database.DatabaseError;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.database.ValueEventListener;
    import com.lorentzos.flingswipe.SwipeFlingAdapterView;

    import java.util.ArrayList;
    import java.util.List;

    public class MainActivity extends AppCompatActivity {


private cards cards_data[];
private arrayAdapter arrayAdapter;
private int i;
private FirebaseAuth mAuth;
private String currentUId;
private DatabaseReference usersDb;




ListView listView;
List<cards> rowItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    usersDb = FirebaseDatabase.getInstance().getReference().child("Users");

    mAuth = FirebaseAuth.getInstance();
    currentUId = mAuth.getCurrentUser().getUid();
    checkUserPreferences();


    rowItems = new ArrayList<cards>();

    // al.add("javascript");
    // al.add("php");

    arrayAdapter = new arrayAdapter(this, R.layout.item, rowItems );
   // al.add("javascript");
   // arrayAdapter.notifyDataSetChanged();


    SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView)     
findViewById(R.id.frame);

    flingContainer.setAdapter(arrayAdapter);
    flingContainer.setFlingListener(new         

SwipeFlingAdapterView.onFlingListener() {
        @Override
        public void removeFirstObjectInAdapter() {
            // this is the simplest way to delete an object from the Adapter     
(/AdapterView)
            Log.d("LIST", "removed object!");
            rowItems.remove(0);
            arrayAdapter.notifyDataSetChanged();
            }

        @Override
        public void onLeftCardExit(Object dataObject) {
            //Do something on the left!
            //You also have access to the original object.
            //If you want to use it just cast it (String) dataObject


            cards obj = (cards) dataObject;
            String userId = obj.getUserId();

usersDb.child(userId).child("connections").child("pass").
child(currentUId).setValue(true);

            isConnectionMatch(userId);
            Toast.makeText(MainActivity.this,"Pass",     
Toast.LENGTH_SHORT).show();

            }

        @Override
        public void onRightCardExit(Object dataObject) {

            cards obj = (cards) dataObject;
            String userId = obj.getUserId();
            usersDb.child(userId).child("connections").child("meet").
child(currentUId).setValue(true);

            isConnectionMatch(userId);
            Toast.makeText(MainActivity.this,"Meet",     
Toast.LENGTH_SHORT).show();


            }

        @Override
        public void onAdapterAboutToEmpty(int itemsInAdapter) {
            // Ask for more data here
            }

        @Override
        public void onScroll(float scrollProgressPercent) {
            }
        }
    );


    // Optionally add an OnItemClickListener
    flingContainer.setOnItemClickListener(new 
SwipeFlingAdapterView.OnItemClickListener() {
        @Override
        public void onItemClicked(int itemPosition, Object dataObject) {

            Toast.makeText(MainActivity.this,"Clicked", 
Toast.LENGTH_SHORT).show();

            }
        }
    );
}

private void isConnectionMatch(String userId) {
    DatabaseReference currentUserConnectionsDb =     
usersDb.child(currentUId).child("connections").
child("meet").child(userId);
    currentUserConnectionsDb.addListenerForSingleValueEvent(new 
ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                Toast.makeText(MainActivity.this, "New Match", 
Toast.LENGTH_LONG).show();
                usersDb.child(dataSnapshot.getKey()).child("connections").
child("matches").child(currentUId).setValue(true);

usersDb.child(currentUId).child("connections").child("matches").
child(dataSnapshot.getKey()).setValue(true);
                }
            }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            }
        }
    );
}


private String userGender;
private String searchGender;

public void checkUserPreferences(){
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference userDb = usersDb.child(user.getUid());
    userDb.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            if (dataSnapshot.getKey().equals(user.getUid())){
                if (dataSnapshot.exists()){
                    if (dataSnapshot.child("gender") != null){
                        userGender =     
dataSnapshot.child("gender").getValue().toString();
                        searchGender = "Female";
                        switch (userGender) {
                            case "Male":
                                searchGender = "Female";
                                break;
                            case "Female":
                                searchGender = "Male";
                                break;
                        }
                        getSearchGender();
                    }
                }

            }
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            }
        }
    );
}





public void getSearchGender(){
    usersDb.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            if (dataSnapshot.exists() && 
!dataSnapshot.child("connections").child("pass").hasChild(currentUId) && 
!dataSnapshot.child("connections").child("meet").hasChild(currentUId) && 
dataSnapshot.child("gender").getValue().toString().equals(searchGender)) {
                String profileImageUrl = "default";
                if
 (dataSnapshot.child("profileImageUrl").getValue().equals("default")) {
                    profileImageUrl = 
dataSnapshot.child("profileImageUrl").getValue().toString();
                    }
                cards item = new cards(dataSnapshot.getKey(), 
dataSnapshot.child("name").getValue().toString(), profileImageUrl);
                rowItems.add(item);
                arrayAdapter.notifyDataSetChanged();
                }
            }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    }
    );
}

public void logoutUser(View view) {
    mAuth.signOut();
    Intent intent = new Intent(MainActivity.this, 
ChooseLoginRegistrationActivity.class);
    startActivity(intent);
    finish();
    return;
    }

public void gotoSettings(View view) {
    Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
    intent.putExtra("userGender", userGender);
    startActivity(intent);
    return;
    }
}

标签: androidcrash

解决方案


使用我在这篇文章中的原始文件,唯一需要的更改是取消注释 1 行并添加另一行(都在 Gradle 文件中)

PROJECT APP取消注释gms行并从原始帖子更新版本

dependencies {
    classpath 'com.android.tools.build:gradle:3.1.2'
    classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.5.4'
    classpath 'com.google.gms:google-services:3.2.0'
}

MODULE APP 添加到文件的最底部

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

我还必须将 google-service 版本从 3.0.1 更新到 3.2.0。不需要其他任何东西。我现在稍微领先于我原来的问题是我的应用程序在更新(单击确认按钮)上传的照片后崩溃。照片存储在 Firebase 数据库存储中,但在寻求更多帮助之前,我将对此进行一些故障排除。感谢@VIKAS SHARMA 的建议


推荐阅读