1

How do I open and write to a file in an Android class outside an activity?

FileWriter is my external class, initialized from MainActivity. The following line in FileWriter:

FileOutputStream fos = openFileOutput("filename", Context.MODE_PRIVATE);

Yields this compilation error:

The method openFileOutput(String, int) is undefined for the type FileWriter

I guess that the class requires some application context - how do I pass it?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • Look at this http://stackoverflow.com/questions/9095610/android-fileinputstream-read-txt-file-to-string/9095689#comment16807274_9095689 question's answer and comments.. – user370305 Sep 20 '12 at 06:18

1 Answers1

3

Simply pass a Context object to the FileWriter class and change your call to this:

FileOutputStream fos = context.openFileOutput("filename", Context.MODE_PRIVATE);

Hope this helps.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • How does this look on the caller's end? Which context object should I pass? – Adam Matan Sep 20 '12 at 06:16
  • @AdamMatan, If you're initializing FileWriter from the MainActivity, then FileWriter fw = new FileWriter(this); will do the job. – Egor Sep 20 '12 at 06:19
  • Possible solution is to state the name of the class, `FileWriter fw = new FileWriter(YourClass.this)` or `FileWriter fw = new FileWriter(getApplicationContext());` – Tobias Moe Thorstensen Sep 20 '12 at 08:38