openFileOutput 中的空指针
我正在尝试从不是 Activity 类的类中使用 openFileOutput
。当我写下面的内容时,它给了我空指针异常-
try {
Context con = null;
fosCAM = con.openFileOutput(camFile, Context.MODE_PRIVATE);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
任何人都可以帮助我吗?
I'm trying to use openFileOutput
from a class which is not Activity class. When I'm writing something following, it gives me null pointer exception-
try {
Context con = null;
fosCAM = con.openFileOutput(camFile, Context.MODE_PRIVATE);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Can anyone help me please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您在非活动类中使用它,请尝试以下操作:
在您的活动类中尝试创建一个上下文,然后将其传递给
类中的类构造函数,在类构造函数和函数中获取上下文(这将保存文件) )获得一个额外的参数,即 Context 。现在使用 yourContext.openFileOutput ,与此相同:
现在应该可以了:)
try this if you are using it in non Activity Class:
in your Activity Class try to create a Context and then pass it to your Class Constructor
in your class get the context in class constructor and in your function (which is going to save the file ) get an extra parameter which is Context . now use yourContext.openFileOutput , the same as this :
now it should be ok :)
您收到空指针异常,因为您将上下文变量 con 设置为 null,然后使用 con.openFileOutput 引用它。
您在活动中的什么地方使用此代码?
如果此代码位于您的 Activity 中,只需删除 Context 变量并调用 openFileOutput。您可以这样做,因为 Activity 派生自 Context。如果代码位于另一个类中,您应该将上下文传递到该类中并使用它。
You're receiving a null pointer exception because you're setting the Context variable con to null and then referencing it with con.openFileOutput.
Where are you using this code, in an activity?
If this code is in your Activity, just remove the Context variable and call openFileOutput. You can do this because Activity derives from Context. If the code is in another class you should pass a context into the class and use it.
如果您从活动开始第二个课程,您可以将您的上下文传递给它。
getBaseContext() 将返回您的上下文,但您应该从 Activity 或同等类中调用它。
If you are starting your second class from an Activity, you can pass it your context.
getBaseContext() will return your context, but you should call it from an Activity or equal class.