NullPointerException异常在onResume调用服务时 [英] NullPointerException when calling service in onResume

查看:201
本文介绍了NullPointerException异常在onResume调用服务时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图进行呼叫的服务,并且基于所述响应,将用户重定向到一个不同的活性(登录)。

如果我迫不及待要做到这一点,直到说,点击一个按钮,然后它工作正常(因为业务绑定),但如果我这样做onResume,然后我得到以下异常:

  ERROR / AndroidRuntime(2226):致命异常:主要
    java.lang.RuntimeException的:无法恢复活动{...} MyActivity:
        显示java.lang.NullPointerException
 

和我的code是:

  FooService接口FooService接口;

@覆盖
保护无效的OnStart(){
    super.onStart();

    意向意图=新的意图(这一点,FooService.class);
    bindService(意向,fooServiceConnection,Context.BIND_AUTO_CREATE);
}

@覆盖
保护无效onResume(){
   //我将承担该服务将受吗?
   super.onResume();
   做一点事();
}
 

解决方案

是什么让你认为 FooService接口 onResume点存在()

在调用 bindService()是异步的。当它发生时它会发生。你不能 DoSomething的()直到 onServiceConnected()被调用,而 onServiceConnected()可能没有被调用的时间 onResume()之称。

和,如果的get() FooService接口正在执行I / O,你需要重写你的应用程序的网络以移动关闭主应用程序线程,并到后台线程。

I am attempting to make a call to a service, and based on the response, redirect the user to a different activity (a login).

If I wait to do this until say, a button click, then it works fine (since the service is bound), but if I do it onResume, then I get the following exception:

ERROR/AndroidRuntime(2226): FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to resume activity {...MyActivity}: 
        java.lang.NullPointerException

and my code is:

FooService fooService;

@Override
protected void onStart() {
    super.onStart();

    Intent intent = new Intent(this, FooService.class);
    bindService(intent, fooServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onResume() {
   //I would assume the service would have bound by now?
   super.onResume();
   doSomething();
}

解决方案

What makes you think that fooService exists at the point of onResume()?

The call to bindService() is asynchronous. It will happen when it happens. You cannot doSomething() until onServiceConnected() is called, and onServiceConnected() may not have been called by the time onResume() is called.

And, if get() on fooService is doing network I/O, you need to rewrite your app to move that off the main application thread and onto a background thread.

这篇关于NullPointerException异常在onResume调用服务时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆