From the course: Android Development Essential Training: Manage Data with Kotlin
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Read files from internal storage
From the course: Android Development Essential Training: Manage Data with Kotlin
Read files from internal storage
- After caching data in a local file, you can then read it into memory. If the data is there, you can avoid having to call the web service again. Add this new function to the file helper class. Place it within the companion object. The name of the function will be readTextFile{app: Application} and it'll receive a reference to the current application object. And it'll return a nullable string. As I did previously, create an instance of the file object. I'll just copy and past this code from the save function. And then check to see whether the file exists with if (file.exists()) if it does, then you can return the expression file.readText all the work of the input and output streams is done for you by this Kotlin extension function. If the file doesn't exist though, return null. So that's one way of writing the code. In Kotlin you can improve this code a bit, by returning the if statement as an expression. I'll move the cursor to after the keyword if, and then I'll use an intention…