java.lang.FileNotFoundException in Android/Kotlin even though file is present - android

I have a data class called Contact which has a companion object property 'allContacts: List' which returns contacts after parsing them from a JSON file.
Relevant code:
val allContacts: List<Contact>
get() {
val json = JSONObject(File("app/src/main/res/data/contacts.json").readText()).getJSONArray("contacts")
val contacts = mutableListOf<Contact>()
...
I do indeed have a contacts.json in res/data package. (data package created manually).
Here's the proof:
Why is this happening? Is the contacts.json file not included in the final .apk?
I have tried logging the current path of the app using
Log.i('.MainActivity', System.getProperty('user.dir'))
But always get . in Logcat.
EDIT: I decompiled the apk in Android Studio and found no traces of contacts.json

Your file doesn't exist in the same project directory you expect it to.
You have to create a resource directory raw and paste your file in there.
Then, you can reference your file as R.raw.contacts wherever you need to reference the file.
Reading the file is another story.
I found it best to create a separate top-level extension function for reading and returning the file contents
fun Activity.readFile(fileID: Int): String {
val inputStream = this.resources.openRawResources(fileID)
return inputStream.use{it.readText()} // Returns entirety of file contents as string.
}

Related

Rename Realm DB file name in Android

I have a Realm DB file, with name "abc.realm". How to change this name to something else? Should I just replace the file name using IO operations or can I do it with migrations? Not able to find any satisfactory answer neither on the web nor on StackOverflow.
Realm stores 2 files, the realm itself and a .lock file. So if you call your realm "abc.realm", then next to this file there is also "abc.realm.lock".
The way to go about renaming your realm file is,
Make sure you find the location of both files
Rename both files with the same name but keeping the ".lock" extension on the lock file
Modify the path to the realm that you pass to the RealmConfigurationBase inheritor
Clearly before doing any of this, make sure to backup your database, just in case.
I don't know what programming language you're writing your android application in, so I'll go with a skeleton in pseudocode
private void BackupRealmFile(string realmLocation, string saveLocation)
{
// make a copy of the file and store it somewhere
}
void YourMainMethod()
{
BackupRealmFile("some/path", "your/backup/path");
IOLib.RenameFile("some/path/abc.realm", "some/path/newName.realm");
IOLib.RenameFile("some/path/abc.realm.lock", "some/path/newName.realm.lock");
var config = new RealmConfiguration("some/path/newName.realm");
// maybe some more settings on your conf
var realm = Realm.GetInstance(config);
}
I hope this helps.

javaClass.getResourceAsStream returns null even though the file is in the specified location

I am trying to access a .json file in src/main/resources in an android project but I keep getting that the variable input is null
I've made sure that the file is in the specified location.
private val CREDENTIALS_FILE_PATH = "src/main/resources/credentials.json"
private var input = javaClass.getResourceAsStream(CREDENTIALS_FILE_PATH)
I'm not sure why this is happening. Is my syntax wrong?
Thanks!

Saving and updating Object array in a file in internal storage Android

I am new to android. I want to save an object containing two strings in a file in the internal storage of the phone. It can be like an array of pairs of strings.
I want to read an array of objects from the file. I also want to update this file(add and delete entries from the app itself)
Attaching my class file
package com.example.ratingfinder.model
class Friend (val platformName: String, val HandleName: String){
//some member functions
}

How to save a ByteArray in the internal storage in Kotlin Android?

I'm trying to save a file containing a ByteArray in the internal storage of my Android in Kotlin, but every example I find is always telling me to use this:
val file = File(context.filesDir, name)
But context isn't defined, and idk what it's suposed to be. What's the supposed definition of the var context?
Thanks!
Replace context with this.getApplicationContext()
val file = File(this.getApplicationContext().filesDir, name)

Read local file from project directory | Kotlin Multiplatform Mobile | KMM

I am trying to read JSON file which is saved in my project locally and want to fetch and read using Kotlin Multiplatform Mobile, so I can share with Android and iOS
Following approch I'm doing:
In commonMain :
package com.example.readJSON.shared
import kotlinx.serialization.Serializable
#Serializable
data class DataRequest(
val dataRegimenRequest: List<DataRegimenRequest>?
)
expect class FileResource(location: String){
val json: String?
}
In androidMain :
package com.example.readJSON.shared
actual class FileResource actual constructor(location: String) {
actual val json: String? = this::class.java.classLoader!!.getResource(location)?.readText()
}
In iosMain :
package com.example.readJSON.shared
actual class FileResource actual constructor(location: String) {
actual val json: String? = null //TODO: write a code to read from local file
}
Can someone will help me, how can I fetch my local JSON file for iOS?
For Android, I am able to read local JSON file.
You'll probably need to write some gradle to copy the file to your iOS app source, then load it by reading iOS resource files from the Bundle. It's a little hard to follow, but we push in a Swift function to handle that here. You could write that code in iOS Kotlin as well.
You might be able to add the file to Xcode directly without needing to copy it in Gradle. From Xcode, right-click your source folder and select "Add Files to ___", then point it at the file. If all of your source is in a single repo, you should be able to point at that file with a relative path from Xcode, and load it at runtime.
For Android, you'd probably want to put that file in assets rather than load it with the class loader, but that's a different discussion.

Categories

Resources