0

I'm trying to get started writing to a file in Kotlin on Android. I found this answer: here

The answer suggests doing a:

val path = context.getFilesDir()

However, this doesn't work for me. The IDE complains that context is an unresolved reference. So I guess this needs to be declared and initialised first somewhere. Any ideas where I am going wrong? What should I do to fix this?

James Read
  • 419
  • 2
  • 7
  • 13
  • As is covered by [a comment on the answer that it appears you copied from](https://stackoverflow.com/questions/45193941/how-to-read-and-write-txt-files-in-android-in-kotlin#comment77389118_45202002), `getFilesDir()` is a method on `Context`; your `Activity` is a subtype of `Context`. – CommonsWare Oct 29 '22 at 22:27
  • @CommonsWare my activity is declared as ```class MainActivity : AppCompatActivity() {```. How do I make it a subtype of Context? – James Read Oct 29 '22 at 22:37
  • It already *is* a subtype of `Context`. If your line of code is in some function in `MainActivity`, just call `getFilesDir()`. Note that there are many books and courses on Android app development that cover these basics. If it helps, [here are several free books of mine](https://commonsware.com/catalog) to get you started! – CommonsWare Oct 29 '22 at 22:41
  • @CommonsWare This produces the runtime error ```Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference``` – James Read Oct 29 '22 at 22:45
  • 1
    If you are attempting to declare `path` as a property of `MainActivity`, that will not work. In general, you cannot call methods on `Activity` or supertypes safely until after `super.onCreate()` is called in your activity's `onCreate()`. If you are careful, you could get away with `val path by lazy { getFilesDir() }`. – CommonsWare Oct 29 '22 at 22:48
  • @CommonsWare OK. I see. Many thanks. I have it working now. BTW I see you have written many books. Very impressive. – James Read Oct 29 '22 at 22:52

0 Answers0