2014-03-12 60 views
0

我在Service中有ServiceHandler,如下所示。將內容傳遞給內部類返回nullpointerexception

public class AdhocFinderService extends Service{ 
Handler someHandler = new Handler(){ 

    //this method will handle the calls from other threads.  
    public void handleMessage(Message msg) { 

      Toast.makeText(AdhocFinderService.this,"display", Toast.LENGTH_SHORT).show(); 
    } 
}; 

在線程類

Message status = adhocFinderService.someHandler.obtainMessage(); 
Bundle data = new Bundle(); 
     data.putString("SOMETHING", "dist"); 
     Log.d(TAG,data.toString()); 
     status.setData(data); 
     adhocFinderService.someHandler.sendMessage(status); 

當我運行此我得到NullpointerException

03-12 13:13:14.542: E/AndroidRuntime(2862): FATAL EXCEPTION: main 
03-12 13:13:14.542: E/AndroidRuntime(2862): java.lang.NullPointerException 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at android.content.ContextWrapper.getResources(ContextWrapper.java:80) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at android.widget.Toast.<init>(Toast.java:89) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at android.widget.Toast.makeText(Toast.java:231) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at com.example.v2papp.AdhocFinderService$1.handleMessage(AdhocFinderService.java:43) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at android.os.Handler.dispatchMessage(Handler.java:99) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at android.os.Looper.loop(Looper.java:143) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at android.app.ActivityThread.main(ActivityThread.java:4196) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at java.lang.reflect.Method.invokeNative(Native Method) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at java.lang.reflect.Method.invoke(Method.java:507) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 
03-12 13:13:14.542: E/AndroidRuntime(2862):  at dalvik.system.NativeStart.main(Native Method) 

我想我所做的是正確的。可能有人正確me.Thanks

回答

0

最後我想出的解決方案,從一個線程來服務發佈的消息。如果沒有正確實施Thread類的,您將不能發佈消息。下面的代碼工作正常。

Message status = adhocFinderService.someHandler.obtainMessage(); 

除非你傳遞服務的實例,它的線程傳遞一個null值。