简体   繁体   English

将数据写入内部文件 - ContextWrapper NullPointerException

[英]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.

相关问题 NullPointerException用于Android ContextWrapper - NullPointerException for android ContextWrapper 尝试将文件写入内部数据时不断获取NullPointerException - Keep getting NullPointerException when trying to write file to internal data ContextWrapper.getFilesDir()中出现NullPointerException的原因 - Reasons for NullPointerException from ContextWrapper.getFilesDir() BackupManager.dataChanged中ContextWrapper.getPackageName上的NullPointerException - NullPointerException on ContextWrapper.getPackageName in BackupManager.dataChanged 使用SQLiteOpenHelper时ContextWrapper.openOrCreateDatabase中的NullPointerException - NullPointerException in ContextWrapper.openOrCreateDatabase when using SQLiteOpenHelper 将文件写入内部存储 - Writing file to internal storage 写入文件时,Android NullPointerException - Android NullPointerException when writing to file android.content.contextwrapper.getsystemservice上的java.lang.nullpointerexception(Contextwrapper.java:386) - java.lang.nullpointerexception at android.content.contextwrapper.getsystemservice(Contextwrapper.java:386) 使用Apache POI写入Excel文件时发生NullPointerException - NullPointerException on writing excel file with apache poi 将信息从linkedhashmap写入文件时,发生NullPointerException - NullPointerException when writing information from linkedhashmap to a file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM