Search code examples
androidarraysloopskotlinsharedpreferences

Converting an int array of Drawable images to a string array of their filenames


I'm using SharedPreferences to save an array of Drawables as Int (which is later used to set setImageResource)

There's some logic I need to perform on SharedPreferences that requires me to get the actual filename, NOT the Int representation of the drawable.

My code is the following:

val imagesFromSaved = PrefsContext(context).savedLocations

imagesFromSaved prints the following:

[2131135903, 2131165414, 2134135800, 2131765348]

I need to be able to print the actual filename. Like this.

["image_one", "image_two", "image_three", "image_four"]

The closest I got was using getString with one single Int. But I'm not sure how to iterate over all the items in the array to convert everything to the string representation.

val test = context.resources.getString(2131135903)

Prints: res/drawable-nodpi-v4/image_one.webp

How can I iterate over my SharedPreferences to generate an array of Drawable filenames, instead of the Int representation of the resource?


Solution

  • To iterate through int array and convert them to strings you can use map function:

    val imagesFromSaved = PrefsContext(context).savedLocations
    val imagesNames: List<String> = imagesFromSaved.map {
        context.getResources().getResourceEntryName(it)
    }
    

    map transforms the list of objects to a list of objects of another type. The resulting imagesNames should contain the names of images.