0

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?

3
  • 1
    You want the resources.getResourceEntryName() function instead. Commented Dec 29, 2021 at 1:17
  • @MikeM. Would I just use a for loop to create the new array of Strings from imagesFromSaved? Commented Dec 29, 2021 at 5:03
  • Sorry, I didn't realize the loop was part of the unknown. Sergey's got a proper example in their answer below. Commented Dec 29, 2021 at 10:36

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

Thanks for answering. Looks like I just need to simply convert my array of Int to a string array using the getResourceEntryName function. Trying to work on that now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.