Skip to content

Instantly share code, notes, and snippets.

@voquanghoa voquanghoa/ContextExts.kt
Last active Mar 25, 2019

Embed
What would you like to do?
Snipet to read file from asset/internal storage on Android with Kotlin
import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* Created by Hoa Vo on 1/18/19.
*/
fun Context.readAssetAsString(fileName: String): String = this.assets.open(fileName).use {
String(it.readBytes())
}
inline fun <reified T: Any> Context.readAsset(fileName: String): T =
Gson().fromJson(this.readAssetAsString(fileName), object: TypeToken<T>() {}.type)
fun Context.readFileAsString(fileName: String): String = this.openFileInput(fileName).use {
String(it.readBytes())
}
inline fun<reified T: Any> Context.readFile(fileName: String): T =
Gson().fromJson(this.readFileAsString(fileName), object: TypeToken<T>() {}.type)
fun Context.writeFile(fileName: String, data: Any){
this.openFileOutput(fileName, Context.MODE_PRIVATE).use { it.write(Gson().toJson(data).toByteArray()) }
}
//Use
articles.addAll(context.readAsset("articles.json"))
...
context.writeFile("data.json", articles);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.