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?
CodePudding user response:
According to your description, I suggest you should do as follows:
- firstly, save the str which is your description fileName
- Then get the fileName from sp
- In the end, you have to use the str to generate the drawable id
//get the R.draw.fileName,it result is fileName
val fileName = context.getResources().getResourceEntryName(R.drawable.arrow_back)
// then use SharedPreferences get the str, To generate ID
val id = context.getResources().getIdentifier(fileName, "drawable", context.getPackageName());
// then use the id in imageView
imegeView.setImageResource(id)
CodePudding user response:
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.