【问题标题】:NullPointer exception and FileInputStreamNullPointer 异常和 FileInputStream
【发布时间】:2013-07-26 02:11:09
【问题描述】:

当我执行FileInputStream ifs=openFileInput(fileName); 行时,我有一个 NPE,我得到了一个 NPE。执行时得到相同的 NPE

FileInputStream ifs=getApplicationContext().openFileInput(fileName);

完整的堆栈跟踪在这里。

07-25 22:00:35.852  25063-25063/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at com.ollien.flashcarder.MainActivity.setPagerFile(MainActivity.java:353)
at com.ollien.flashcarder.SetsFragment$1.onItemClick(SetsFragment.java:47)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1215)
at android.widget.ListView.performItemClick(ListView.java:4506)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2959)
at android.widget.AbsListView$1.run(AbsListView.java:3645)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)

有人可以帮忙吗?我不太清楚为什么会这样。文件名不为空,等于"hi there.txt"Thanks!

【问题讨论】:

  • 你能检查一下 getApplicationContext() 是否返回 null 吗?只需要一个日志。如果您确定文件名不为空
  • 您是否偶然在onItemClicksetPagerFile 中致电attachBaseContext()?我问是因为getApplicationContext()openFileInput() 都调用了mBaseContext.SOMETHING,所以如果你将它设置为null,那么这就解释了NPE。
  • @Nicholas getApplicationContext();当我尝试 System.out 时抛出 NPE
  • @Jonathan 不,我实际上从未听说过 attachBaseContext()。我应该为此做些什么?
  • 不,可能不是。但是,对openFileInput() 的调用实际上只是对mBase.openFileInput() 的调用,getApplicationContext() 是类似的。唯一可能成为空指针堆栈顶部的方法是mBase 为空。可以把代码发到setPagerFile()吗?

标签: java android nullpointerexception fileinputstream


【解决方案1】:

解决方案: 确保您的 Context 不为空,例如,我通过函数参数将其传入 public void setPagerFile(String fileName,Context mContext){ 然后使用 mContext 作为你的上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多