Android What Is Wrong with Openfileoutput

android what is wrong with openFileOutput?

Your method should be as follows. Takes in an extra Context as a parameter. To this method you can pass your Service or Activity

public static void save(String filename, MyObjectClassArray[] theObjectAr, 
Context ctx) {
FileOutputStream fos;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);

ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObjectAr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}

The method OpenFileOutput() is undefined !

Those are methods defined on the Context class, not methods defined in your class. When your code was part of an Activity, it could use a convenience method openFileInput() in its Activity base class to access the underlying Context.getApplicationContext().openFileInput() (and similarly for openFileOutput()).

Now you'll have to replace those with the direct calls to the underlying Context methods.

How to fix Cannot resolve method 'openFileOutput(java.lang.String, int)'

View.OnClickListener is not a context (and not the one you need). You need to use the Context from your calling activity

   public static void writeData(ArrayList<String> items, Context context){
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(items);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

openFileOutput does not create the file

It should definitely work. How are you checking if the file actually exists? What I mean is: without root access when you use e.g. a File Manager you won't be able to access the /data/.. folders, but you can access that file from your own application.

NullPointerException at openFileOutput in Activity

This is proved to be a feature of Android 2.3.3 emulator installed here as a part of SDK. The problem does not occur if I use a real device with Android 2.3.3. Also the code works ok if I use Android 4.0.3 emulator. So, if some weird things happen, tests in another environment can shed some light. I hope this can help someone else in similar problem solving.

openFileOutput FileNotFoundException

I have to apologize for leaping before I looked on this one. I kinda panicked while reading the documentation. After some testing, I found that openFileOutput() does, in fact, work as advertised and will create a file if it's not found, not just throw an FnF exception as I feared. Apparently, the FnF throw was added in case the Activity's application directory does not exist.

Again, my apologies but hopefully, this might help others who are confused by the documentation.



Related Topics



Leave a reply



Submit