Kotlin can't import JSON file, even with explicit path

706 Views Asked by At

I am trying to import a local JSON file into an Android app using Kotlin and Android Studio, however the app can not seem to find the file. Even with an explicit path the JVM can not seem to get at the file. I have tried making a .txt file, and JVM can not find that either. Klaxon's tutorials do not work because the Parser class has been deprecated; which doesn't matter anyway because that's not where the error is. And yes, the file exists in the directory, and it is spelled that way.

fun parse(name: String) : Any? {
    val inputStream: InputStream = File("C:\\Users\\Athena\\AndroidStudioProjects\\AD340HW1\\app\\zombie_movies.json").inputStream()
    val lineList = mutableListOf<String>()

    //val cls = Parser::class.java
    //inputStream.bufferedReader().useLines { lines -> lines.forEach {lineList.add(it)  } }
    //val strArray = arrayOfNulls<String>(lineList.size)
    return lineList
 }

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.athena.ad340hw1/com.example.athena.ad340hw1.ZombieMovies}: java.io.FileNotFoundException: C:\Users\Athena\AndroidStudioProjects\AD340HW1\app\zombie_movies.json (No such file or directory)

2

There are 2 best solutions below

0
On

So what I ended up doing is just hosting the JSON on a server, and pulling it off the server. That ended up being better then working with it on my local machine, because in the future that data needs to be accessed from a remote device. I guess my root error was in trying to proceed too slowly, too methodically; I should have just fired up the server that I needed and been done with it.

0
On

To use a text file or any other external file you have to have the android app ask the user to grant permission. There is code out there that will popup a box asking for permission to use the file system. Here is a link to get you started I'm sure there are many other good tutorials on the subject. https://developer.android.com/training/permissions/requesting.html