在服务中使用共享首选项时出错

时间:2017-11-29 14:29:54

标签: android nullpointerexception firebase-cloud-messaging

我尝试访问服务中的共享首选项,但它一直让我犯这个错误并且应用程序崩溃:java.lang.RuntimeException: Unable to instantiate service com.ct.kitapp.PubNubFirebase: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

这是firebase实例服务:

public class PubNubFirebase extends FirebaseInstanceIdService {
    public static final String PREFS_NAME = "PubNubUserFile";
    SharedPreferences sharedPref = this.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    String pubKey = sharedPref.getString("pubkey","default");
    String subKey = sharedPref.getString("subkey","default");

    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.i("FireBaseID", "Refreshed token: " + refreshedToken);

        try {
            JsonObject jsonToken = new JsonObject();
            jsonToken.addProperty("tokenJson", refreshedToken);
            Log.i("jsonToken", String.valueOf(jsonToken));
            sendTokenToPubNub(jsonToken);
        }catch(Exception e){
            Log.i("jsonToken", "Exception: " + e);
        }



    }

    private void sendTokenToPubNub(JsonObject refreshedToken) {
        //String msg = "{registrationToken : " + refreshedToken + "}";
//        PNConfiguration pnConfiguration = new PNConfiguration();
//        pnConfiguration.setPublishKey(pubKey);
//        pnConfiguration.setSubscribeKey(subKey);
        //Log.i("firepub",pubKey);
        //PubNub pubnub = new PubNub(pnConfiguration);

        PNConfiguration pnConfiguration = new PNConfiguration();
        pnConfiguration.setPublishKey(pubKey);
        pnConfiguration.setSubscribeKey(subKey);

        PubNub pubnub = new PubNub(pnConfiguration);
        pubnub.publish().channel("test_channel3").message(refreshedToken).async(new PNCallback<PNPublishResult>() {
            @Override
            public void onResponse(PNPublishResult result, PNStatus status) {
                // Check whether request successfully completed or not.
                if (!status.isError()) {
                    Log.i("FireToken", String.valueOf(status.getStatusCode()));
                    Log.i("FireToken", status.getCategory().toString());
                    // Message successfully published to specified channel.
                }
                // Request processing failed.
                else {
                    Log.i("FireToken", String.valueOf(status.getStatusCode()));
                    Log.i("FireToken", status.getCategory().toString());
                    Log.i("FireToken", status.getErrorData().toString());
                    // Handle message publish error. Check 'category' property to find out possible issue
                    // because of which request did fail.
                    //
                    // Request can be resent using: [status retry];
                }
            }
        });
      }
    }

在配置PubNub时,我需要从共享首选项访问PubNub键以在sendTokenToPubNub方法中使用。感谢您的帮助,谢谢。

完整logcat:

11-29 20:08:00.749 825-871/? E/Sensors: sns_reg_la.c(188):reg read: offset 2304, num bytes: 1
11-29 20:08:00.750 767-1307/? E/qti_sensors_hal: processInd: pickup data: state: 1.000000 flag: 0.000000 SAM TS: 2802400084 HAL TS:85513644537973 elapsedRealtimeNano:85513705042098
11-29 20:08:00.754 825-871/? E/Sensors: sns_reg_la.c(188):reg read: offset 2304, num bytes: 1
11-29 20:08:00.761 767-767/? E/qti_sensors_hal: sendEnableReq:sensor(android.sensor.proximity) Sending enable to svc no:21
11-29 20:08:00.767 767-1309/? E/qti_sensors_hal: reportSingleEvent: prox data: 5.000305 raw:16.000000 2989118976.000000 SAM TS: 2756542590 HAL TS:84114184882746 elapsedRealtimeNano:85513722376733
11-29 20:08:00.772 767-767/? E/qti_sensors_hal: sendCancel:sensor(android.sensor.proximity) Sending cancel to svc no:21
11-29 20:08:00.773 961-2421/? E/fpc_fingerprint_hal: screen_state_loop screen ON 0
11-29 20:08:00.780 767-767/? E/qti_sensors_hal: sendEnableReq:sensor(android.sensor.proximity) Sending enable to svc no:21
11-29 20:08:00.786 767-1309/? E/qti_sensors_hal: reportSingleEvent: prox data: 5.000305 raw:16.000000 2989118976.000000 SAM TS: 2756542590 HAL TS:84114184882747 elapsedRealtimeNano:85513741396941
11-29 20:08:00.868 754-23867/? E/msm8974_platform: platform_get_snd_device_backend_index: no hw_interface set for device 69
11-29 20:08:00.868 754-23867/? E/audio_hw_utils: send_app_type_cfg_for_device: Couldn't get the backend index for snd device handset-mic-re-three ret=-22
11-29 20:08:00.869 754-23867/? E/ACDB-LOADER: Error: ACDB AudProc vol returned = -19
11-29 20:08:00.869 754-23867/? E/ACDB-LOADER: Error: ACDB_CMD_GET_AFE_COMMON_TABLE_SIZE Returned = -19


                                              [ 11-29 20:08:00.869   754:23867 D/         ]
                                              Failed to fetch the lookup information of the device 00000091 
11-29 20:08:00.869 754-23867/? E/ACDB-LOADER: Error: ACDB AFE returned = -19
11-29 20:08:00.889 1415-3827/? E/DeviceKeyHandler: receive keyguard done, process gesture action
11-29 20:08:00.902 767-2153/? E/qti_sensors_hal: sendCancel:sensor(com.oneplus.sensor.pocket) Sending cancel to svc no:31
11-29 20:08:00.958 767-2153/? E/qti_sensors_hal: sendCancel:sensor(android.sensor.proximity) Sending cancel to svc no:21
11-29 20:08:00.961 767-2153/? E/qti_sensors_hal: sendEnableReq:sensor(android.sensor.proximity) Sending enable to svc no:21
11-29 20:08:00.965 6134-6134/? E/ContentDetectionService: updateSceneDetectionState() - No SceneDetector
11-29 20:08:01.026 767-1309/? E/qti_sensors_hal: reportSingleEvent: prox data: 5.000305 raw:18.000000 2989118976.000000 SAM TS: 2802411071 HAL TS:85513979835821 elapsedRealtimeNano:85513980872462
11-29 20:08:02.128 3641-23562/? E/ctxmgr: [AppIntervalImpl]closeInterval: ongoing
11-29 20:08:02.137 3641-23562/? E/ctxmgr: [ProducerStatusImpl]updateStateForNewContextData: inactive, contextName=6
11-29 20:08:03.754 32548-32548/? E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
11-29 20:08:03.767 32548-32548/? E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
11-29 20:08:05.685 32548-32548/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:05.685 32548-32548/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:05.701 793-2427/? E/SurfaceFlinger: Failed to find layer (SurfaceView - InputMethod#0) in layer parent (no-parent).
11-29 20:08:05.702 793-876/? E/SurfaceFlinger: Failed to find layer (Background for - SurfaceView - InputMethod#0) in layer parent (no-parent).
11-29 20:08:06.633 1415-2674/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:06.635 1415-2674/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
11-29 20:08:06.662 19772-19772/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:06.663 19772-19772/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:07.521 1415-1465/? E/ActivityManager: Sending non-protected broadcast action_change_isolate_application_theme from system uid 1000 pkg null
                                                  java.lang.Throwable
                                                      at com.android.server.am.ActivityManagerService.checkBroadcastFromSystem(ActivityManagerService.java:20827)
                                                      at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:21503)
                                                      at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:21645)
                                                      at com.android.server.pm.PackageManagerService$6.run(PackageManagerService.java:14631)
                                                      at android.os.Handler.handleCallback(Handler.java:789)
                                                      at android.os.Handler.dispatchMessage(Handler.java:98)
                                                      at android.os.Looper.loop(Looper.java:164)
                                                      at android.os.HandlerThread.run(HandlerThread.java:65)
                                                      at com.android.server.ServiceThread.run(ServiceThread.java:46)
11-29 20:08:07.524 4989-5028/? E/ExternalAccountType: Unsupported attribute viewStreamItemActivity
11-29 20:08:07.525 4944-4988/? E/ExternalAccountType: Unsupported attribute viewStreamItemActivity
11-29 20:08:07.531 4989-5028/? E/ExternalAccountType: Unsupported attribute readOnly
11-29 20:08:07.532 4944-4988/? E/ExternalAccountType: Unsupported attribute readOnly
11-29 20:08:07.552 2689-2689/? E/OPUtils: removeMultiApp ,cloudthat.ct.kitapp
11-29 20:08:07.583 2788-23934/? E/OPSkin:ThemeIntentService: cloudthat.ct.kitapp
11-29 20:08:07.588 3741-3741/? E/RegisteredServicesCache: Next Tag=services
11-29 20:08:07.588 3741-3741/? E/RegisteredServicesCache: 1invalidateCache:WriteServiceStateToFile
11-29 20:08:07.588 3741-3741/? E/RegisteredServicesCache:  Writing service state Data Always
11-29 20:08:07.613 4731-4731/? E/Finsky: [2] com.google.android.finsky.wear.bk.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
11-29 20:08:07.791 32548-23961/? E/SQLiteLog: (1) no such column: true
11-29 20:08:07.794 32548-23962/? E/SQLiteLog: (1) no such column: true
11-29 20:08:07.807 3572-23958/? E/DropboxRealtime: Unknown package: cloudthat.ct.kitapp
                                                   java.lang.IllegalArgumentException: Unknown package: cloudthat.ct.kitapp
                                                       at android.os.Parcel.readException(Parcel.java:1946)
                                                       at android.os.Parcel.readException(Parcel.java:1888)
                                                       at android.content.pm.IPackageManager$Stub$Proxy.getInstallerPackageName(IPackageManager.java:4207)
                                                       at android.app.ApplicationPackageManager.getInstallerPackageName(ApplicationPackageManager.java:1972)
                                                       at agdj.a(:com.google.android.gms@11746440:45)
                                                       at agct.a(:com.google.android.gms@11746440:3)
                                                       at agbv.a(:com.google.android.gms@11746440:10)
                                                       at com.google.android.gms.stats.service.DropBoxEntryAddedChimeraService.onHandleIntent(:com.google.android.gms@11746440:15)
                                                       at buh.handleMessage(Unknown Source:6)
                                                       at android.os.Handler.dispatchMessage(Handler.java:105)
                                                       at android.os.Looper.loop(Looper.java:164)
                                                       at android.os.HandlerThread.run(HandlerThread.java:65)
11-29 20:08:08.645 776-862/? E/ANDR-PERF-OPTSHANDLER: perf_lock_rel: updated /sys/class/scsi_host/host0/../../../clkscale_enable with 1
                                                       return value 2
11-29 20:08:15.671 755-6076/? E/vendor.qti.bluetooth@1.0-wake_lock: Release wakelock is released 
11-29 20:08:17.447 755-6076/? E/vendor.qti.bluetooth@1.0-wake_lock: Release wakelock is released 
11-29 20:08:20.596 825-871/? E/Sensors: sns_reg_la.c(188):reg read: offset 2304, num bytes: 1
11-29 20:08:20.755 1415-18585/? E/LocationManagerService: requestLocationUpdates: uid=10075, pid=25558, provider=gps, package=com.google.android.apps.maps listener= android.location.ILocationListener$Stub$Proxy@36c6985 intent= null
11-29 20:08:20.763 825-871/? E/Sensors: sns_reg_la.c(188):reg read: offset 2304, num bytes: 1
11-29 20:08:20.777 825-871/? E/Sensors: sns_reg_la.c(188):reg read: offset 2304, num bytes: 1
11-29 20:08:21.328 1415-2671/? E/LocationManagerService: removeUpdates: uid=10075, pid=25558, intent=null, package=com.google.android.apps.maps listener android.location.ILocationListener$Stub$Proxy@f0f4471 intent= null
11-29 20:08:21.337 825-871/? E/Sensors: sns_reg_la.c(297):reg write: offset 10752, num bytes: 126
11-29 20:08:21.347 825-871/? E/Sensors: sns_reg_la.c(297):reg write: offset 1792, num bytes: 24
11-29 20:08:24.165 767-2153/? E/qti_sensors_hal: sendEnableReq:sensor(android.sensor.significant_motion) Sending enable to svc no:40
11-29 20:08:24.194 767-2153/? E/qti_sensors_hal: sendCancel:sensor(android.sensor.significant_motion) Sending cancel to svc no:40
11-29 20:08:32.303 924-31289/? E/installd: Failed to delete /data/app/vmdl1573728457.tmp: No such file or directory
11-29 20:08:32.347 4989-5028/? E/ExternalAccountType: Unsupported attribute viewStreamItemActivity
11-29 20:08:32.347 4944-4988/? E/ExternalAccountType: Unsupported attribute viewStreamItemActivity
11-29 20:08:32.357 4944-4988/? E/ExternalAccountType: Unsupported attribute readOnly
11-29 20:08:32.412 3741-3741/? E/RegisteredServicesCache: Next Tag=services
11-29 20:08:32.413 3741-3741/? E/RegisteredServicesCache: 1invalidateCache:WriteServiceStateToFile
11-29 20:08:32.413 3741-3741/? E/RegisteredServicesCache:  Writing service state Data Always
11-29 20:08:32.429 4989-5028/? E/ExternalAccountType: Unsupported attribute readOnly
11-29 20:08:32.493 1415-2671/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:32.495 1415-2671/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
11-29 20:08:32.514 4731-4731/? E/Finsky: [2] com.google.android.finsky.wear.bk.a(3): onConnectionFailed: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null, message=null}
11-29 20:08:32.529 1415-18582/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:32.530 1415-18582/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
11-29 20:08:32.565 24145-24162/? E/zygote64: Failed sending reply to debugger: Broken pipe
11-29 20:08:32.883 1415-3800/? E/BoostFramework: BoostFramework() : Exception_1 = java.lang.NoSuchMethodException: perfIOPrefetchStart [int, class java.lang.String]
11-29 20:08:32.884 1415-3800/? E/BoostFramework: Exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[])' on a null object reference
11-29 20:08:33.449 24145-24145/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: cloudthat.ct.kitapp, PID: 24145
                                                   java.lang.RuntimeException: Unable to instantiate service cloudthat.ct.kitapp.PubNubFirebase: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
                                                       at android.app.ActivityThread.handleCreateService(ActivityThread.java:3554)
                                                       at android.app.ActivityThread.-wrap4(Unknown Source:0)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1778)
                                                       at android.os.Handler.dispatchMessage(Handler.java:105)
                                                       at android.os.Looper.loop(Looper.java:164)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6809)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
                                                       at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:168)
                                                       at cloudthat.ct.kitapp.PubNubFirebase.<init>(PubNubFirebase.java:24)
                                                       at java.lang.Class.newInstance(Native Method)
                                                       at android.app.ActivityThread.handleCreateService(ActivityThread.java:3551)
                                                       at android.app.ActivityThread.-wrap4(Unknown Source:0) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1778) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                       at android.os.Looper.loop(Looper.java:164) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:6809) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

1 个答案:

答案 0 :(得分:0)

使用getBaseContext(),如下所示:

 SharedPreferences sharedPref = getBaseContext().getSharedPreferences