开发者

Why does this Android FileOutputStream throw a NullPointerException?

There does not seem to be any Android manifest permission that needs to be set for file io.

public class Device extends Activity {
    private static final Configuration config = new Configuration();
    ...
    private boolean applyMenuChoice(MenuItem item) {
        switch (item.getItemId()) {
        ...
        case R.id.menuSave:
            ...
            configuration.modify(name, to, from, user);
            configuration.write();
            ...

public class Configuration extends Activity {
    private final static String CONFIG = "config.txt";
    private static StringBuilder config = new StringBuilder();
    ...
    public void write() {
        try {
            FileOutputStream fos = openFileOutput(CONFIG, Context.MODE_PRIVATE);
            fos.write(config.toString()开发者_开发百科.getBytes());
            ...


Replacing the illegal instantiation of an activity with correct methods resolved this issue. Thank you very much (again) Falmarri.


Where are you trying to write your file to? If it's on the SD-card of the device, you need to set the WRITE_EXTERNAL_STORAGE-permission in your android-manifest. You may also need to set a path instead of just using a filename.


The exception is thrown in this scenario when this pointer is incorrect. You probably created the activity using its ctor like a regular object and not using start activity of an intent. In this case dont invoke openFileOutput or this.openFileOutput , but you should send the context which you are in as an argument to write() function, and use this context, i.e.:

write(Context context)
{
     context.openFileOutput(...)
     ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜