Search code examples
androidsharedpreferencesr.java-filesave-image

How to store Image Resource/Name in preferences


I have a scenario:

Suppose, there are two images: one.png and two.png. User will have to select an image, I have to save image's name or Resource ID in preferences. Later when user will open the app, I will load the image user selected last time.

So my Question is how am I going to save it in preferences? Is saving Resource ID for image correct? Does R.java contents remain same once app is installed? I just don't want to save bitmap anywhere since it is already present in drawables.

Please help me clear my concept. Thanks.


Solution

  • You should save the name, i.e (one, two in your case)

    Later, you can get IDs of resources by name

    String imageNameFromPreferences= getLastUsedImageFromPref();
    //get resource id by name
    final int resourceIdOfLastUsedImage = resources.getIdentifier(imageNameFromPreferences, "drawable", 
       context.getPackageName());
    //use this id to set the image anywhere
    imageView.setBackgroundResource(resourceIdOfLastUsedImage)