【问题标题】:NullPointer exception in ContextWrapperContextWrapper 中的 NullPointer 异常
【发布时间】:2011-09-11 01:23:24
【问题描述】:

我有一个名为 FileGeneration 的类,它扩展了 Activity
在 FileGeneration 我有一个方法叫做

protected OutputStream openAndWriteFile() {

   // Set the Context-mode
   int cxt = Context.MODE_PRIVATE;

   // Check if we are not going to clear the file and the file exists
   if (!clearFile && (new File(this.fileName)).exists()) {

      // Append to the file
      cxt = Context.MODE_APPEND;
   }

   // Try to open the file to write to
   try {

      // Open the File using the Context
      this.os = openFileOutput(this.fileName, cxt);

   } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }

   // Return the OutputStream
   return this.os;
}

我在 Logcat 中得到这个输出

06-08 15:31:43.733: ERROR/AndroidRuntime(2850): java.lang.NullPointerException
06-08 15:31:43.733: ERROR/AndroidRuntime(2850):    at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
06-08 15:31:43.733: ERROR/AndroidRuntime(2850):    at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
06-08 15:31:43.733: ERROR/AndroidRuntime(2850):    at dataconnection.FileGeneration.openAndWriteFile(FileGeneration.java:278)

类中的第 278 行是

this.os = openFileOutput(this.fileName, cxt);

但是当我在 Logcat 中打印带有参数的方法时,它会说

openFileOutput(Preferences.xml, 1);

文件不存在,但是openFileOutput说如果不存在就会创建它

有什么问题?

【问题讨论】:

    标签: android android-activity nullpointerexception android-context


    【解决方案1】:

    我用(new ContextWrapper(ctx)).openFileOutput(this.fileName, cxt)解决了这个问题

    【讨论】:

      【解决方案2】:

      尝试写一个测试看看是否this.filename == null,并使用Log.d(String,String)方法输出结果。

      【讨论】:

      • 我已经尝试过使用 Log.d("ProgramName", "openFileOutput(" + this.fileName + ", " + cxt + ")");这给出了问题中的输出
      猜你喜欢
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2014-02-24
      相关资源
      最近更新 更多