skip to Main Content

I’m having a problem with the app created, I looked for many solutions and none of them work. Neither putting the code that tells me, nor updating everything… It says it’s something related to Firebase, but I don’t know how to solve it, here is my error and code.

 Process: com.paradigma.SIGEPedidos, PID: 14396
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paradigma.SIGEPedidos/com.paradigma.SIGEPedidos.views.StartActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.paradigma.SIGEPedidos. Make sure to call FirebaseApp.initializeApp(Context) first.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3835)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2325)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8633)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
 Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.paradigma.SIGEPedidos. Make sure to call FirebaseApp.initializeApp(Context) first.
    at com.google.firebase.FirebaseApp.getInstance(FirebaseApp.java:184)
    at com.google.firebase.iid.FirebaseInstanceId.getInstance(com.google.firebase:firebase-iid@@20.1.6:1)
    at com.paradigma.SIGEPedidos.views.StartActivity.refreshTokenDevice(StartActivity.java:41)
    at com.paradigma.SIGEPedidos.views.StartActivity.onCreate(StartActivity.java:37)
    at android.app.Activity.performCreate(Activity.java:8207)
    at android.app.Activity.performCreate(Activity.java:8191)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3808)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2325) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:246) 
    at android.app.ActivityThread.main(ActivityThread.java:8633) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130) 

Build Grade (app):

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

android {
    compileSdkVersion 31

    defaultConfig {
        applicationId "com.paradigma.SIGEPedidos"
        minSdkVersion 19
        targetSdkVersion 31
        versionCode 20
        versionName "1.20.0-alpha"
        multiDexEnabled true

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            resValue("string", "PORT_NUMBER", "8081")
        }
    }
    compileOptions {
        targetCompatibility = 1.8
        sourceCompatibility = 1.8
    }

}
apply plugin: 'com.google.gms.google-services'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation project(path: ':EmptyMessageLayout')
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

    implementation 'com.android.support:multidex:2.0.1'
    def room_version = "2.2.5"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation "androidx.cardview:cardview:1.0.0"
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.paging:paging-runtime:2.1.2'
    implementation "androidx.work:work-runtime:2.4.0"


    implementation 'com.google.firebase:firebase-ads:17.0.0'
    implementation 'com.google.firebase:firebase-database:20.0.5'
    implementation 'com.google.firebase:firebase-core:21.0.0'
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
    implementation 'com.google.firebase:firebase-analytics:17.4.0'
    implementation 'com.firebaseui:firebase-ui-auth:3.1.2'
    implementation "com.google.firebase:firebase-perf:19.0.10"

    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

    debugImplementation 'com.amitshekhar.android:debug-db-encrypt:1.0.6'

    implementation 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
    implementation 'com.google.android:flexbox:2.0.1'

    implementation 'com.paradigma.components:components:1.0.0'

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

Build Grade (Module):

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

def USERNAME = properties.getProperty('USERNAME')
def PASSWORD = properties.getProperty('PASSWORD')

buildscript {

    repositories {
        google()
        jcenter()
        maven {
            url 'http://dl.bintray.com/amulyakhare/maven'
            allowInsecureProtocol = true
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        classpath "com.google.firebase:firebase-plugins:2.0.0"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:4.3.10'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            credentials {
                username USERNAME
                password PASSWORD
            }

            authentication {
                basic(BasicAuthentication)
            }

            url "https://api.bitbucket.org/2.0/repositories/" + COMPANY + "/" + REPOSITORY_NAME + "/src/release"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Main Activity:

    package com.paradigma.SIGEPedidos.views.main;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.TextAppearanceSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.paradigma.SIGEPedidos.R;
import com.paradigma.SIGEPedidos.component.searchtoolbar.SearchToolbar;
import com.paradigma.SIGEPedidos.repositories.LoginRepository;
import com.paradigma.SIGEPedidos.utils.PreferencesMethods;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.navigation.NavigationView;
import com.paradigma.SIGEPedidos.views.login.LoginActivity;
import com.paradigma.SIGEPedidos.views.UpdateActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    DrawerLayout drawer;
    NavigationView navigationView;
    ActionBarDrawerToggle toggle;

    private FloatingActionButton cartFAB;

    MaterialToolbar toolbar;
    private ToolbarHelper toolbarHelper;
    AppBarLayout appBarLayout;
    private CollapsingToolbarHelper collapsingToolbarHelper;
    private SearchViewHelper searchViewHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(RECEIVER_CLOSE, new IntentFilter("close"));
        registerReceiver(RECEIVER_UPDATE, new IntentFilter("update"));
        setContentView(R.layout.activity_articulos);

        toolbar = findViewById(R.id.toolbar);
        toolbarHelper = new ToolbarHelper(this, toolbar);
        setSupportActionBar(toolbar);

        appBarLayout = findViewById(R.id.toolbar_layout);
        collapsingToolbarHelper = new CollapsingToolbarHelper(this, appBarLayout);
        collapsingToolbarHelper.configure();
        collapsingToolbarHelper.getTxtCliente().setOnClickListener(
                v -> goTo(R.id.action_to_listasDePreciosFragment)
            );

        cartFAB = findViewById(R.id.button_ver_pedidos);

        searchViewHelper = new SearchViewHelper(this,appBarLayout);

        initNavigationDrawer();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        AppBarConfiguration appBarConfiguration =
                new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration);
        SearchToolbar searchToolbar = findViewById(R.id.search_toolbar);
        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
            if(destination.getId() == R.id.ArticulosFragment){
                collapsingToolbarHelper.setExpanded(true, true);
                cartFAB.setVisibility(View.VISIBLE);
                navigationView.setCheckedItem(R.id.action_articulos);
                drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                toggle.syncState();
                toolbarHelper.configureToolbar();
                toolbar.setNavigationOnClickListener(v -> drawer.openDrawer(GravityCompat.START));
            }else{
                if(searchToolbar.isOpen()) searchToolbar.close();
                cartFAB.setVisibility(View.GONE);
                collapsingToolbarHelper.setExpanded(false,true);
                drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                toolbar.setNavigationOnClickListener(v -> onBackPressed());
            }
        });
    }

    public CollapsingToolbarHelper getCollapsingToolbarHelper() {
        return collapsingToolbarHelper;
    }

    public SearchViewHelper getSearchViewHelper() {
        return searchViewHelper;
    }

    @Override
    public void onBackPressed() {
        if(drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START); return;
        }
        if(collapsingToolbarHelper.isOpenDrawerLayoutFilter()){
            collapsingToolbarHelper.closeDrawerLayoutFilter(); return;
        }

        NavController navController =
                Navigation.findNavController(this, R.id.nav_host_fragment);

        if( navController.getCurrentDestination().getId() == R.id.ArticulosFragment) {
            showDialogSalir();
        }else{
            super.onBackPressed();
        }
    }

    public void showDialogSalir(){
        SpannableString spanTitle = new SpannableString("Cerrar");
        spanTitle.setSpan(new ForegroundColorSpan(
                        ContextCompat.getColor(this, R.color.colorPrimary)),
                0, spanTitle.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );

        String msg = "¿Desea salir de la aplicación?";

        new MaterialAlertDialogBuilder(this)
                .setTitle(spanTitle)
                .setMessage(msg).setPositiveButton(
                "Aceptar", (dialog, which) -> {
                    dialog.dismiss();
                    super.onBackPressed();
                }).setNeutralButton("Cancelar", (dialog, which) -> dialog.dismiss()).show();
    }
    @Override
    @SuppressLint("NonConstantResourceId")
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId){
            case R.id.action_create_objeto_facturable:
                goTo(R.id.action_to_CreateObjectoFacturableFragment);break;
            case R.id.action_pendientes:
                goTo(R.id.action_to_pedidosPendientesFragment);break;
            case R.id.action_enviados:
                goTo(R.id.action_to_pedidosApiFragment);break;
            case R.id.action_listaDePrecios:
                goTo(R.id.action_to_listasDePreciosFragment);break;
            case R.id.action_clientes_sin_alta:
                goTo(R.id.action_to_ClientesSinAltaFragment);break;
            case R.id.action_log_out:
                this.logOut();break;
            default:break;
        }
        return false;
    }

    private void logOut() {
        LoginRepository.getInstance().logOut(this);
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }

    private void goTo(int fragment){
        Navigation.findNavController(this,R.id.nav_host_fragment).navigate(fragment);
        drawer.closeDrawer(GravityCompat.START);
    }

    public void initNavigationDrawer(){
        drawer = findViewById(R.id.drawer_layout_main);
        navigationView = findViewById(R.id.articulos_nav_view);
        toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        navigationView.setNavigationItemSelectedListener(this);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        initMenuStyles(navigationView.getMenu());

        TextView username = navigationView.getHeaderView(0).findViewById(R.id.textview_username);
        String usernameString = PreferencesMethods.getUsername(this) + "!";
        username.setText(usernameString);

        navigationView.setNavigationItemSelectedListener(this);
    }

    private void initMenuStyles(Menu menu) {
        int itemCategoryColor = R.style.item_category_color;
        setStyleCategory(R.id.cuenta_menu_category, itemCategoryColor, menu);
        setStyleCategory(R.id.listas_menu_category, itemCategoryColor, menu);
        setStyleCategory(R.id.pedido_menu_category, itemCategoryColor, menu);
        setStyleCategory(R.id.action_articulos, R.style.item_category_rounded,menu);
    }

    private void setStyleCategory(int category,int style, Menu menu){
        MenuItem tools= menu.findItem(category);
        SpannableString s = new SpannableString(tools.getTitle());
        s.setSpan(new TextAppearanceSpan(this, style), 0, s.length(), 0);
        tools.setTitle(s);
    }

    private final BroadcastReceiver RECEIVER_CLOSE = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = "Se ha cerrado la sesión";

            if(intent.getStringExtra("message_close") != null){
                message = intent.getStringExtra("message_close");
            }

            MaterialAlertDialogBuilder messageDialog = new MaterialAlertDialogBuilder(context)
                    .setTitle("Sesión Finalizada")
                    .setMessage(message)
                    .setPositiveButton("Cerrar", (dialog, which) -> dialog.dismiss());
            messageDialog.setOnDismissListener(dialog -> finish());
            messageDialog.show();
        }
    };

    private final BroadcastReceiver RECEIVER_UPDATE = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent){goToUpdateActivity();}
    };

    @Override
    protected void onDestroy() {
        try{
        unregisterReceiver(RECEIVER_UPDATE);
        }catch (Exception ignored){}
        unregisterReceiver(RECEIVER_CLOSE);
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        unregisterReceiver(RECEIVER_UPDATE);
        super.onPause();
    }

    @Override
    protected void onResume(){
        super.onResume();
        registerReceiver(RECEIVER_UPDATE, new IntentFilter("update"));
    }

    private void goToUpdateActivity(){
        Intent intent = new Intent (this, UpdateActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        this.finishAffinity();
        startActivity(intent);
    }
}

I hope you can fix the error so I can run it, because every time I try it crashes instantly. If you need any more code, let me know! Thank you. Previously I had another error but I was able to fix it, and because of that it generated this new one.

2

Answers


  1. Did you add "google-services.json" in app level module?

    Also add this FirebaseApp.initializeApp(this);

    in you Application or in MainActivity class below:

    super.onCreate(savedInstanceState); 
    
    Login or Signup to reply.
  2. That error happened to me when I executed the tests (Instrumentation tests) and I was obtaining the FirebaseAnalytics as follows val analytics = Firebase.analytics, I had to change the way I got the instance as: firebaseInstance = FirebaseAnalytics.getInstance(context), the problem with this is that we need to provide the context, so this is an impediment if we need to use the FirebaseAnalytics in other places where the context is not available. Here is an implementation using the Singleton pattern.

    object FirebaseAnalyticsUtils {
        lateinit var firebaseInstance: FirebaseAnalytics
    
        fun initAnalytics(context: Context) {
            firebaseInstance = FirebaseAnalytics.getInstance(context)
        }
    
        fun logScreenView(screenName: String) {
            firebaseInstance.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
                param(FirebaseAnalytics.Param.SCREEN_NAME, screenName)
                param(FirebaseAnalytics.Param.SCREEN_CLASS, screenName)
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search