在Android中启动服务时出现Java.lang.NullPointerException [英] Java.lang.NullPointerException when starting a service in android

查看:250
本文介绍了在Android中启动服务时出现Java.lang.NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我想从一个活动中启动一项服务.所以我在活动onCreate方法中给出了这个

hi all, I want to start a service from an activity. So I gave this in my activity onCreate method

try
        {
        Intent gforce=new Intent(GPS2Activity.this,GforceService.class);
        gforce.putExtra("NUMBER", number);
        ct.startService(gforce);
        }

        catch (Exception e) {
           Toast.makeText(this, e.toString(), 2000).show();
       }



在我的服务类onStart()方法中,我放入了



in my service class onStart() method I put

@Override
	public void onStart(Intent intent, int startId) {
		
		phn=intent.getStringExtra("NUMBER");
		
		super.onStart(intent, startId);
	}



然后,它给出了Java.lang.NullPointerEsception.原因是什么,我该怎么解决.

谢谢,



Then it gives Java.lang.NullPointerEsception. What is the reason for that and what can I do to solve this problem.

Thanks,

推荐答案

在需要对象的情况下,应用程序尝试使用null时抛出.其中包括:

  • 调用null对象的实例方法.
  • 访问或修改null对象的字段.
  • 以null的长度作为数组的长度.
  • li>
  • 访问或修改null的插槽,就好像它是一个数组.
  • 将null抛出,就好像它是一个Throwable值一样.
Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.


您应始终检查intent参数是否为null.在文档中:

提供给startService(Intent)的Intent,如给定.如果服务在其进程消失后正在重新启动,并且以前返回了除START_STICKY_COMPATIBILITY以外的任何内容,则该值为null.

此外,不建议使用onStart().您应该在服务中使用onStartCommand().
You should always check the intent parameter for null. In the docs:

The Intent supplied to startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.

Furthermore, onStart() is deprecated. You should use onStartCommand() in your service.


这篇关于在Android中启动服务时出现Java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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