[英]Writing Data to Internal File - ContextWrapper NullPointerException
I'm creating a file for internal storage, and I'm running into a problem when the data is written.我正在为内部存储创建一个文件,并且在写入数据时遇到了问题。 I know that it retrieves the right data when it's called (I used a Logcat tag to check that it was), but as soon as it tries to open the FileOutputStream, it says that there is a NullPointerException on the second line:
我知道它在被调用时检索了正确的数据(我使用 Logcat 标签来检查它是否正确),但是一旦它尝试打开 FileOutputStream,它就会说第二行有一个 NullPointerException:
static ContextWrapper wrap = new ContextWrapper(context);
FileOutputStream gamesave = wrap.openFileOutput (FILENAME, Context.MODE_PRIVATE);
gamesave.write(DATA.getBytes());
gamesave.close();
I've looked at other questions and I can't figure out why the NullPointerException is there, it seems to be following the right procedure.我已经查看了其他问题,但我无法弄清楚为什么会出现 NullPointerException,它似乎遵循了正确的程序。
I think you have the wrong Context in your context
var (ie ApplicationContext).我认为您的
context
变量(即ApplicationContext)中有错误的上下文。 Try using the context directly - without the Wrapper.尝试直接使用上下文 - 不使用 Wrapper。
Why are you creating a ContextWrapper?为什么要创建 ContextWrapper? There is no reason to do that.
没有理由这样做。 Just use the Context you have at hand -- the Activity if you are an Activity, or one passed in to your code if not.
只需使用您手头的 Context —— 如果您是 Activity,则使用 Activity,如果不是,则使用传递给您的代码的 Context。
Note that it is perfectly fine to use the Application as a Context for this.请注意,将应用程序用作上下文是非常好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.