null pointer in openFileOutput

柔情痞子 提交于 2019-12-24 09:50:09

问题


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?


回答1:


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.




回答2:


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 :

public void SaveFileIntoStorage(String xml,Context cn) throws IOException

now it should be ok :)




回答3:


If you are starting your second class from an Activity, you can pass it your context.

new SecondClass(getBaseContext()).start();

getBaseContext() will return your context, but you should call it from an Activity or equal class.



来源:https://stackoverflow.com/questions/5428228/null-pointer-in-openfileoutput

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!