【问题标题】:Passing context to inner class returns nullpointerexception将上下文传递给内部类返回 nullpointerexception
【发布时间】:2014-04-17 01:10:21
【问题描述】:

我在Service 中有一个ServiceHandler,如下所示。

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)

我认为我所做的是正确的。有人能纠正我吗。谢谢

【问题讨论】:

    标签: android multithreading handler android-toast


    【解决方案1】:

    您可能希望使用 getApplicationContext() 而不是 AdhocFinderService.this

    请注意,我不是专家,但我认为这个答案会满足您的需求:Android Toast started from Service only displays once

    【讨论】:

      【解决方案2】:

      最后,我找到了将消息从线程发布到服务的解决方案。如果没有正确实现 Thread 类,您将无法发布消息。下面的代码运行良好。

      Message status = adhocFinderService.someHandler.obtainMessage();
      

      除非您将服务实例传递给线程,否则它会传递null 值。

      【讨论】:

        猜你喜欢
        • 2013-09-10
        • 2021-12-04
        • 2020-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-05
        相关资源
        最近更新 更多