views:

235

answers:

1

It's perfectly described here how to do it, the only problem: He doesnt know the function openFileOutput();

private void saveSettingsFile() {
          String FILENAME = "settings";
          String string = "hello world!";

          FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); //openFileOutput underlined red
          try {
            fos.write(string.getBytes());
            fos.close();
          } catch (IOException e) {
            Log.e("Controller", e.getMessage() + e.getLocalizedMessage() + e.getCause());
          }
}

Those are the relevant packages I imported:

import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
+1  A: 

Have a look at this example of using a FileOutputStrem from the Examples on dev.android.com. It should give you an idea of how to use it correctly.

fredley
Thank u. I will look into it. however, I still would prefer to get this 5 lines working. I mean the author of the document I referred to above cant be fundamentally wrong.
OneWorld
you need to call openFileOutput on a context. Try `context.openFileOutput()`
fredley
Ok, good suggestion. However I dont have the variable or object "context". How do I create or get it?
OneWorld
Your context is your Activity. If this code is in a View then all views are created with a context as an argument. If this code is in another class you'll have to pass in the context as an argument as you would with a View.
fredley
In which class the method is placed? The openFileOutput should be invoked on Context instance (i.e. activity).
Konstantin Burov
@Konstantin Yup, exactly what I just said.
fredley
It's a class whose instance can be called from everywhere by its static function Controller.getInstance(). That's the singleton way of providing classes, I guess.This class provides data like the session, user data and so on. These stuff needs to be present in all activities.
OneWorld
It's like a model for all activities through the lifetime of this app. Shall I pass the context of any Activity in its onCreate()-Method to my Controller? Doesnt that cause nasty Bugs by Threading and so on?
OneWorld
@OneWorld Then you need to pass in a context instance in the method and invoke openFileInput on the instance.
Konstantin Burov
Do I have to update this reference in the controller when intenting a new activity? In my case activities dont request directly the controller to load this settings file. Model classes do that.
OneWorld
Well you can reference application context in the controller, just pass it into getInstance method. To obtain application context you have to invoke getApplicationContext on activity.
Konstantin Burov
One more question: Is it enough to pass "getApplicationContext()" to my Controller only while creating my 1st activity? Is that passed by reference? So, is that just a pointer to the application context?
OneWorld