I am to using firebase-messaging
library and trying to fetch the token using below method on app launch.
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(InstanceIdResult instanceIdResult) { String token = instanceIdResult.getToken(); // print token } });
App crashes on the launch itself giving
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.iid.FirebaseInstanceId.getInstanceId()' on a null object reference
AndroidManifest
<service
android:name=".MyFirebaseMessageService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Build.gradle :
implementation 'com.google.android.gms:play-services-analytics:16.0.5'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
Also, i have tried to cache the token in SharedPreferences but it seems onNewToken() is never called.
@Override
public void onNewToken(String token) {
super.onNewToken(token);
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preference.edit();
editor.putString("TOKEN",token);
editor.apply();
}
What could be the problem?
There was problem in merged manifest, following service was missing from the merged manifest.
Added same to AndroidManifest.xml
it worked like a charm.
<service android:name="com.google.firebase.components.ComponentDiscoveryService" >
<meta-data
android:name="com.google.firebase.components:com.google.firebase.iid.Registrar"
android:value="com.google.firebase.components.ComponentRegistrar" />
</service>
Everything is working fine now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With