-1

I just want to write and read some data but my app doesn´t know the context. Do I have to define the context before I use it?

I´ve got this code from an answer on: How To Read/Write String From A File In Android

private void writeToFile(String data) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}

Here is how it looks like in Android Studio:

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
L4c0573
  • 333
  • 1
  • 7
  • 23
  • in which class are you trying to use context? apparently it's not declared in somewhere, you can use different approach for activity, fragment and others to get the context – Orhan Obut Mar 18 '16 at 21:36

3 Answers3

5

if your method is inside Activity class, replace context with getApplicationContext(). If not, you need to declare field Context context in your class and set its value from any activity/service.

Wukash
  • 666
  • 5
  • 9
1
context

is a variable. It has not been declared anywhere in your code. It should be an object of Context class. Replace it with

getApplicationContext()

or provide the context through the method's parameters when calling it.

or (most of the times) you can replace

context

with:

this

keyword. May work if your code is inside a class extending the Activity class.

mantlabs
  • 352
  • 2
  • 6
1

Activity is a child of Context, just like Services, the Application class and others.

If you are using this code in an activity, openFileOutput() is an inherited method, so you just need to call it:

... openFileOutput("config.txt", Context.MODE_PRIVATE) ...

If you are inside a fragment, you can call getContext():

... getContext().openFileOutput("config.txt", Context.MODE_PRIVATE) ...

And if you are in another class, you need to get this reference (asking for it in the constructor or in the method call, for example):

private void writeToFile(String data, Context context) {
    ...
    context.openFileOutput("config.txt", Context.MODE_PRIVATE)
    ...
}
Alan Wink
  • 113
  • 10