-2

Я пытаюсь интегрировать FireBase Cloud Messaging в моем приложении с помощью учебника:Попытки вызвать виртуальный метод булева com.google.android.gms.common.ConnectionResult.isSuccess()»на объектной ссылке нулевой

https://www.simplifiedcoding.net/firebase-cloud-messaging-tutorial-android/

Когда я пытаюсь запустить приложение, я получаю исключение Null Pointer:

Вот LogCat:

java.lang.NullPointerException: Attempt to invoke virtual method 
'boolean com.google.android.gms.common.ConnectionResult.isSuccess()' on a null object reference 
                       at com.google.android.gms.common.internal.zzd$zzi.zzh(Unknown Source) 
                       at com.google.android.gms.common.internal.zzd$zzk.zztp(Unknown Source) 
                       at com.google.android.gms.common.internal.zzd$zza.zzc(Unknown Source) 
                       at com.google.android.gms.common.internal.zzd$zza.zzw(Unknown Source) 
                       at com.google.android.gms.common.internal.zzd$zze.zztr(Unknown Source) 
                       at com.google.android.gms.common.internal.zzd$zzd.handleMessage(Unknown Source) 
                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                       at android.os.Looper.loop(Looper.java:145) 
                       at android.app.ActivityThread.main(ActivityThread.java:5942) 
                       at java.lang.reflect.Method.invoke(Native Method) 
                       at java.lang.reflect.Method.invoke(Method.java:372) 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400) 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195) 

Вот мой build.gradle:

buildscript { 
    repositories { 
     mavenCentral() 
    } 
    dependencies { 
     classpath 'com.android.tools.build:gradle:2.0.0' 
     //FireBase dependency 
     classpath 'com.google.gms:google-services:3.0.0' 
    } 
} 
apply plugin: 'android' 


dependencies { 
    compile fileTree(include: '*.jar', dir: 'libs') 
    //FireBase dependency 
    compile 'com.google.firebase:firebase-messaging:10.0.1' 
} 

android { 
    compileSdkVersion 20 
    buildToolsVersion '23.0.3' 
    sourceSets { 
     main { 
      manifest.srcFile 'AndroidManifest.xml' 
      java.srcDirs = ['src'] 
      resources.srcDirs = ['src'] 
      aidl.srcDirs = ['src'] 
      renderscript.srcDirs = ['src'] 
      res.srcDirs = ['res'] 
      assets.srcDirs = ['assets'] 
      jniLibs.srcDirs = ['libs'] 
     } 

     instrumentTest.setRoot('tests') 

     // Move the build types to build-types/<type> 
     // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ... 
     // This moves them out of them default location under src/<type>/... which would 
     // conflict with src/ being used by the main source set. 
     // Adding new build types or product flavors should be accompanied 
     // by a similar customization. 
     debug.setRoot('build-types/debug') 
     release.setRoot('build-types/release') 
    } 
    lintOptions { 
     abortOnError false 
    } 

    compileOptions { 
     sourceCompatibility JavaVersion.VERSION_1_7 
     targetCompatibility JavaVersion.VERSION_1_7 
    } 

    compileOptions { 
     sourceCompatibility JavaVersion.VERSION_1_7 
     targetCompatibility JavaVersion.VERSION_1_7 
    } 

    productFlavors { 
     x86 { 
      ndk { 
       abiFilter "x86" 
      } 
     } 
     arm { 
      ndk { 
       abiFilters "armeabi-v7a", "armeabi" 
      } 
      minSdkVersion 17 
     } 
    } 
    packagingOptions { 
     exclude 'META-INF/DEPENDENCIES' 
     exclude 'META-INF/NOTICE' 
     exclude 'META-INF/LICENSE' 
     exclude 'META-INF/license.txt' 
     exclude 'META-INF/notice.txt' 
    } 
    defaultConfig { 
     minSdkVersion 17 
     applicationId "com.nytshft.evyt" 
    } 
} 
//FireBase 
    apply plugin: 'com.google.gms.google-services' 

Примечание: У меня нет модуля приложения в моем приложении. У меня есть один файл build.gradle.

Связано ли это с build.gradle? На официальном сайте они говорят, чтобы скопировать json-файл в папку приложения. К сожалению, у моего приложения нет такой папки. Вот ProjectView Screenshot. Также говорят, чтобы добавить некоторую зависимость в build.gradle приложения. Поскольку у меня нет какой-либо папки приложений, я делал эти изменения в файле build.gradle проекта.

MyFirebaseInstanceIDService.java:

class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { 

    private static final String TAG = "MyFirebaseIIDService"; 
    @Override 
    public void onTokenRefresh() { 
     // Get updated InstanceID token. 
     String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 
     Log.d(TAG, "Refreshed token: " + refreshedToken); 
     sendRegistrationToServer(refreshedToken); 
    } 

    private void sendRegistrationToServer(String token) { 
     // TODO: Implement this method to send token to your app server. 
    } 

MyFireBaseMessagingService.java

class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "MyFirebaseMsgService"; 
    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 

     Log.d(TAG, "From: " + remoteMessage.getFrom()); 

     // Check if message contains a data payload. 
     if (remoteMessage.getData().size() > 0) { 
      Log.d(TAG, "Message data payload: " + remoteMessage.getData()); 
     } 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
      //Calling method to generate notification 
      //sendNotification(remoteMessage.getNotification().getBody()); 
     } 
     Toast.makeText(getApplicationContext(), "Push notification: " + remoteMessage.getNotification().getBody(), Toast.LENGTH_LONG).show(); 


    } 


    /** 
    * Create and show a simple notification containing the received FCM message. 
    * This method is only generating push notification. 
    * @param messageBody FCM message body received. 
    */ 
    private void sendNotification(String messageBody) { 
     Intent intent = new Intent(this, MainActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.androidwidget_logo) 
       .setContentTitle("FCM Message") 
       .setContentText(messageBody) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
    } 
+0

Интересно, почему мой вопрос в настоящее время downvoted. :(Пожалуйста, помогите! – Rakesh

+1

У вас нет ни одного вашего кода здесь, вот почему, возможно, –

+0

. Зависимости вашей базы битвы также устарели, и вы следуете за сторонним руководством, а не официальным, так что это еще одна проблема. –

ответ

1

После нескольких дней расследования я наконец нашел причину исключения Null Pointer. Был google-play-services.jar, находящийся в папке libs проекта (добавлен для некоторого другого модуля, а не для FireBase). Это противоречит
apply plugin: 'com.google.gms.google-services', который мы добавляем для FireBase.

мне пришлось удалить банку с libs и добавил так же, как зависимость, как это:

compile 'com.google.android.gms:play-services:10.0.1'

0

Многие люди забыли это dependencie compile 'com.google.firebase:firebase-core:9.6.1'. Все зависимости от firebase нуждаются в их ядре, вы можете узнать больше об этом в этом post, не забудьте обновить firebase-messaging до последней версии compile 'com.google.firebase:firebase-messaging:9.6.1'.

Сообщите мне, если я помог вам и хорошее программирование!

+0

Я добавил firebase-core. Не помогает мне :( – Rakesh

+0

Другое, что вам нужно сделать, это переместить это : применить плагин: «com.google.gms.google-services» в нижней части градиента. В документации Google эта строка должна быть последней. –

+0

Did.and обновлен в qn. Тот же результат. Я подозреваю, что он имеет что-то делать с build.gradle. В документе google они упоминают о 2 файлах build.gradle - приложении и проекте. У меня есть только 1 файл build.gradle, который имеет корневой проект. В моем проекте нет папки приложения. так? – Rakesh