为什么当我实例化一个类扩展活动和调用一个方法,使用openFileInput我得到空指针异常



你好,我正在尝试从另一个类调用使用openFileInput(filename)的方法(fileReader)。我在一个扩展BroadcastReceiver的类中做一些处理,我需要读取一个文件,我不能在这个类中调用openFileInput(),所以我创建了一个扩展Activity或IntentService(两者都尝试过)的helper类,这样我就可以实例化它并像这样调用它:

    HelperClass hc = new HelperClass();
    hc.fileReader();

我在fileReader中调用openFileInput的行上得到一个NullPointerException。在我看来,它必须对上下文或构造函数没有正确初始化做一些事情,它只是HelperClass(){super();}。

我怎样才能克服这个?

当您调用openFileInput时,您正在尝试打开与给定上下文相关的文件。因为你是实例化你的HelperClass没有提供一个上下文,它试图打开你的文件使用一个空上下文(因此你的空指针异常)。你能做的就是让你的方法fileReader()接受一个Context对象,然后使用provider Context调用openFileInput。

public void fileReader(Context context) //change the return type if you need
{
  //your code
  //..
  FileInputStream fos = context.openFileInput(filename);
}

将其命名为

hc.fileReader(context); //get the context using "this" or getContext() depending on where you're calling it

或者,你可以让fileReader成为一个静态方法,这样你就不需要创建一个HelperClass的实例来使用它了。

public static void fileReader(Context context) //change the return type if you need
{
      //your code
      //..
      FileInputStream fos = context.openFileInput(filename);   
}

然后使用

调用
HelperClass.fileReader(context);

最新更新