Question

I have a Service and Handler in the Service as shown below.

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();
     }
};

On thread class

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);

When I run this I am getting 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)

I think what I am doing is correct. could some one correct me.Thanks

Was it helpful?

Solution 2

Finally I figured out the solution to posting a message from a thread to service. Without proper implementation of the Thread class you will not be able to post a message. The code below works fine.

Message status = adhocFinderService.someHandler.obtainMessage();

Unless you pass the instance of service to the thread it passes a null value.

OTHER TIPS

You'll probably want to use getApplicationContext() instead of AdhocFinderService.this

Mind you, I'm no expert, but I think this answer will have what you need: Android Toast started from Service only displays once

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top