NullPointerException异常在服务的构造 [英] NullPointerException in Service's constructor

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

问题描述

在我的Andr​​oid项目中,我有一个服务

In my Android project, I have a Service :

public class MyService extends Service{

    //I defined a explicite contructor 
    public MyService(){
       //NullPointerException here, why?
       File dir = getDir("my_dir", Context.MODE_PRIVATE);
    }

    @Override
    public void onCreate(){
      super.onCreate();
      ...
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
        ...
    }

}

我通常知道

,我不应该明确地定义为Android 服务的构造函数。但对我来说,我想用构造函数来创建在我的内部存储的目录。

I know normally, I shouldn't explicitly define a constructor for Android Service. But in my case, I want to use the constructor to create a directory in my internal storage.

当我尝试它,我得到的 NullPointerException异常,我不明白为什么?任何人都可以向我解释为什么我的原因 NullPoineterException 当调用 GETDIR(...)在我的explicite构造?

When I try it, I got NullPointerException, which I don't understand why? Could anyone explain to me the reason why I got NullPoineterException when call getDir(...) in my explicite constructor ?

推荐答案

<一个href=\"http://developer.android.com/reference/android/content/Context.html#getDir%28java.lang.String,%20int%29\"相对=nofollow> GETDIR() 是在上下文的方法

该服务未设置要用作上下文直到的onCreate()

The service is not set up to be used as a Context until onCreate().

基本上,该框架建立服务(和活动为此事)下列方式:

Basically, the framework sets up services (and activities for that matter) the following way:


  1. 创建对象

  2. 设置了上下文,以适当的资源为当前配置

  3. 呼叫的onCreate()的对象

  1. Create the object
  2. Set up the Context, with appropriate resources for the current configuration
  3. Call onCreate() on the object

您不能做任何需要的对象是一个正确设置上下文在步骤1,即成员变量初始化或构造中。

You cannot do anything that requires the object to be a properly set up Context at step 1 i.e. during member variable initialization or constructor.

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

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