How to store Image Resource/Name in preferences

2.4k views Asked by At

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.

3

There are 3 answers

3
Vinay W On BEST ANSWER

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)
1
Kelevandos On

Do something like this:

public List<Integer> myImagesList;

public void createMyImagesList{
    //Here put all the image ids you need into the list
    myImagesList.put(R.id.one);
    myImagesList.put(R.id.two);
} 

And later, when you want to store the user selection, simply store the List position of the selected image.

public Integer obtainUserSelectedImage(int theIdStoredInPrefs){
    return myImageList.get(theIdStoredInPrefs);
}

This way you create a wrapper id, independent from the R.drawable id, as the list will be repopulated with valid ids each time the app is re-run (and possibly, re-built).

1
rekire On

I would just save a hint which image was displayed the last time. I would use something like "img1" and "img2". Then the next time in onCreate load the correct image. In general, saving the resource id should work fine, but if you add and remove new images, it is possible that the ids change. However this can only happen after an update.

Try this code in your onCreate method:

SharedPreferences prefs = context.getSharedPreferences(BuildConfig.APPLICATION_ID + "_preferences", Context.MODE_PRIVATE);
String lastImg = settings.getString("image");
if("img1".equals(lastImg) {
    imageView.setDrawable(R.drawable.img1);
} else if("img2".equals(lastImg) {
    imageView.setDrawable(R.drawable.img2);
}