0

FCM (Firebase Cloud Messaging) initialize issue

I started working on FCM module, I fallowed as per the firebase guidelines. i'm getting two exceptions like RuntimeException and IllegalStateException. Firebase init default but why and what is the issue in FCM.

1. From Android Studio tools -> Firebase -> Cloud Messaging.

2. I fallowed Set up Firebase Cloud Mesasging.

I fallowed below link:

https://firebase.google.com/docs/cloud-messaging/android/client

App : Build.gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-messaging:17.4.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

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

Project : Build.gradle

buildscript {
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath 'com.google.gms:google-services:4.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

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

In MainActivity.class, i trying to get token but app crashes.

 public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String tokenId = FirebaseInstanceId.getInstance().getToken(); //Crashes in this line 
        Log.d("SH", tokenId);
    }
}

in logcat i got two exceptions

 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.package PID: 29368
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.package.testfcm/com.package.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.package. Make sure to call FirebaseApp.initializeApp(Context) first.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2861)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2943)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1630)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6626)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
     Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.package. Make sure to call FirebaseApp.initializeApp(Context) first.
        at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common@@16.0.2:240)
        at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source:1)
        at com.package.MainActivity.onCreate(MainActivity.java:20)
        at android.app.Activity.performCreate(Activity.java:7032)
        at android.app.Activity.performCreate(Activity.java:7023)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1236)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2943) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1630) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6626) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811) 

Finally i found solutions, Now i able to get FCM Token.

In project build.gradle file you need add single line code code i.e., mavenLocal().

Fallow as per the below solutions cross check the project : build.gradle file and app : build.gradle file.

Project : build.gradle

buildscript {
    repositories {
        mavenLocal()  //This is the line you need to add 
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        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
    }
}

allprojects {
    repositories {
        mavenLocal() //This is the line you need to add 
        google()
        jcenter()

    }
}

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

App : build.gradle

apply plugin: 'com.android.application'


android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.testfcm"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'


    implementation 'com.google.firebase:firebase-core:16.0.8'
    implementation 'com.google.firebase:firebase-iid:17.1.1'
    implementation 'com.google.firebase:firebase-messaging:17.5.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'
Community
  • 1
  • 1
PSP
  • 59
  • 8
  • Make sure you have added google json file in your app and check package name in the file with your package name. and finally add FirebaseApp.initializeApp(this); in activity – rajahsekar Mar 27 '19 at 12:59
  • Yes i added google json file. – PSP Mar 27 '19 at 13:07
  • Firebase needs time to connect to it server and gives you the instance referred to your device , give it some time or use a promise to make sure firebase is connected to it server and instance is generated, then perform the action that need firebase instance. – ismail alaoui Mar 27 '19 at 13:46
  • Finally i found a solutions. Just you need to add single line code in project build.gradle file i.e., mavenLocal(); – PSP Mar 28 '19 at 07:20

2 Answers2

0

I can see from your code that you are getting Firebase instance before it had to be initialized. You have to first initialize it then get token using getInstance().

FirebaseApp.initializeApp(this);

Or try the way google documents shows for getting token

FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();


                Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
            }
        });
Abid Khan
  • 2,451
  • 4
  • 22
  • 45
0

Try this way.


In Android Studio GO TO TOOLS Menu.
Then Select Firebase Option.
Provide your firebase enabled google account id-password.
From right side tab select Cloud Messaging.
Then click on setup firebase messaging .
Follow mension steps over there.

Jigar
  • 104
  • 7