Activity 中一个回调方法中调用 invalidateOptionsMenu ();出现空指针异常

Android · codog · 于 发布 · 最后由 twiceyuan回复 · 500 次阅读
96

我启动了一个Service向服务器轮询数据,一旦有新数据就会通过一个回调接口在Activity中更新toolbar上item的图标
我Service中的代码是这样的:

//轮询plan匹配消息
       //这是listener,MainActivity实现了回调接口OnNewMessageListener
         private OnNewMessageListener listener = new MainActivity();        
          //用volley进行服务请求
        StringRequest stringRequestMatchPlan = new StringRequest(Request.Method.POST, MYSEVERADDRESS_MATCH_PLAN, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.d(TAG, "匹配的plan:" + s);
                ReceivedMsgBean receivedMsgBean = (ReceivedMsgBean) GSONUtil.parseJsonWithGson(s, ReceivedMsgBean.class);
                if (receivedMsgBean.getStatus().equals("0") && receivedMsgBean.getMatchPlanList()!= null) {
                    matchPlanList = receivedMsgBean.getMatchPlanList();
                    listener.onNewMatchPlanMessage(matchPlanList);//此处回调
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(Poller.this, "服务器出错", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "匹配的plan,服务器出错");
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("username", username);
                return map;
            }
        };
        RequestQueue requestQueue = MyApplication.getRequestQueue();
        requestQueue.add(stringRequestMatchPlan);

        //这是接口的定义
        public interface OnNewMessageListener{
        void onNewAddFriendMessage(List<ReceivedMsgBean.UserListBean> addFriendList);
        void onNewChatMessage(ArrayList<ChatMsgBean> chatMsglist);
        void onNewMatchPlanMessage(List<ReceivedMsgBean.MatchPlanListBean> matchPlanList);
    }

这是MainActivity中的代码,当调用invalidateOptionsMenu();时报空指针异常

@Override
    public void onNewMatchPlanMessage(List<ReceivedMsgBean.MatchPlanListBean> matchPlanList) {
        Log.d(TAG,"onNewMatchPlanMessage--------"+Thread.currentThread());
        this.matchPlanList = matchPlanList;
        state = STATE_HAVE_NEW_MESSAGE;
        invalidateOptionsMenu();//就是这报错
    }

错误信息是

FATAL EXCEPTION: main
                        Process: com.movie17.yiqimovie, PID: 4153
                        java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                        at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:120)
                        at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:151)
                        at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:31)
                        at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:55)
                        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:205)
                        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
                        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:525)
                        at android.support.v7.app.AppCompatActivity.invalidateOptionsMenu(AppCompatActivity.java:250)
                        at com.movie17.yiqimovie.activity.MainActivity$override.onNewMatchPlanMessage(MainActivity.java:452)
                        at com.movie17.yiqimovie.activity.MainActivity$override.access$dispatch(MainActivity.java)
                        at com.movie17.yiqimovie.activity.MainActivity.onNewMatchPlanMessage(MainActivity.java:0)
                        at com.movie17.yiqimovie.service.Poller$8.onResponse(Poller.java:171)
                        at com.movie17.yiqimovie.service.Poller$8.onResponse(Poller.java:164)
                        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:1)
                        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                        at android.os.Handler.handleCallback(Handler.java:815)
                        at android.os.Handler.dispatchMessage(Handler.java:104)
                        at android.os.Looper.loop(Looper.java:194)
                        at android.app.ActivityThread.main(ActivityThread.java:5556)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at java.lang.reflect.Method.invoke(Method.java:372)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:967)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

各位大神帮帮忙呀,学Android的时间不长,实在是不知道什么原因,谢谢各位大神啦

共收到 1 条回复
53
twiceyuan · #1 ·

消灭零回复,论坛貌似活跃的人很少?

OnNewMessageListener listener = new MainActivity() 的方式肯定是不对的。Activity 只能通过 Context.startActivity[ForResult] 操作来创建而不是直接 new 出来,而且就算可以 new 出来的对象和实际在运行的 Activity 也不是同一个对象。

Service 和 Activity 通讯可以看下 ServiceConnection,通过 IBinder 对象来通信,或者使用广播、一些第三方的 EventBus 之类的库也都可以。建议先简单过下 Android 的官方 Guide 吧 https://developer.android.com/guide/

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册