2017-11-29 12 views
0

나는 서비스에 공유 기본 설정에 액세스하기 위해 노력하고있어하지만 나에게이 오류 및 응용 프로그램 충돌을 던지는 유지 :서비스에 공유 환경 설정을 사용하여 오류를 얻기

: 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

이 중포 기지 인스턴스 서비스

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를 구성 할 때 sendTokenToPubNub 메소드 내에서 사용하려면 공유 환경 설정에서 PubNub 키에 액세스해야합니다. 고마워. 고마워.

전체 로그 캣 :

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(:[email protected]:45) 
                 at agct.a(:[email protected]:3) 
                 at agbv.a(:[email protected]:10) 
                 at com.google.android.gms.stats.service.DropBoxEntryAddedChimeraService.onHandleIntent(:[email protected]: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/[email protected]_lock: Release wakelock is released 
11-29 20:08:17.447 755-6076/? E/[email protected]_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= [email protected] 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 [email protected] 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)  
+0

전체 logcat을 보여주세요, –

+1

제발'this.getSharedPreferences'가 인스턴스 메서드 밖에서 작동하지 않습니다 –

+0

OP가 다시 그런 비밀스러운 대답을 이해할 수 있을지 궁금합니다. – greenapps

답변

1

사용과 같은 getBaseContext() :

SharedPreferences sharedPref = getBaseContext().getSharedPreferences 
+0

나는 이것을 이미 시도했고 똑같은 오류를 던지고 충돌을 일으킨다. –

+0

@ BlackIce2107 null 객체 참조에서 'android.content.SharedPreferences android.content.Context.getSharedPreferences (java.lang.String, int)'가상 메소드를 호출하려고 시도합니다. 분명히 문제는 해당 객체를 가져 오는 데 사용하는 컨텍스트입니다. sharedPrefference – AndroidSmoker74

+0

그래, 거의 다 작동 했어. 도와 주셔서 감사합니다. –

0

하면 "onTokenRefresh"방법에 컨텍스트에 의존 아무것도를 초기화합니다. 컨텍스트는 서비스가 초기화되기 전에는 사용할 수 없습니다. "onCreate"가 호출되기 전에 activites 컨텍스트에서 작업하는 것과 같습니다.

+0

감사의 말을 듣고 내 의구심을 정리하는 데 도움이되었습니다. 이제 새로 고쳐진 토큰이 더 이상 채널에 게시되지 않습니다. –

+0

발생했을 때 예외가 발생합니까? –