Javierd98
Javierd98

Reputation: 810

Android SharedPreferences get drawable if value doesn´t exist

so in my app I need to save and to display an image on a image view, so i use SharedPreferences for saving it, the problem is that, if there is not a saved value, i want to display an image from drawables, and for that I´m using this code:

final ImageButton imgView = (ImageButton) findViewById(R.id.UserImageButton);
String photo = PreferenceManager.getDefaultSharedPreferences(UserActivity.this).getString("Image", String.valueOf(getResources().getDrawable(R.drawable.user, getApplicationContext().getTheme())));//NameOfTheString, StringIfNothingFound
        imgView.setImageBitmap(BitmapFactory.decodeFile(photo));

But if there is no image saved, the drawable is not used on the ImageView, and it doesn´t show anything. How could I fix it?

Upvotes: 0

Views: 657

Answers (2)

PPartisan
PPartisan

Reputation: 8231

There's no requirement to use the default value of your getString() method as a direct path to your drawable. You could simply do the following:

private static final String IMAGE_PREF = "image_pref_key";
private static final String PREF_FAIL_CODE= "no_image_found";

String photo = PreferenceManager.getDefaultSharedPreferences(UserActivity.this).getString(IMAGE_PREF, PREF_FAIL_CODE);

if (photo.equals(PREF_FAIL_CODE) {
    imageView.setImageDrawable(getResources().getDrawable(R.drawable.user));
} 

Upvotes: 1

Viral Patel
Viral Patel

Reputation: 33438

When you are getting the string from default shared preferences, if the value is not stored, set the default value returned to something e.g. "not found"

Now before setting doing setImageBitmap check if the value in your String variable photo is "not found". If it is display the drawable from your resource. Else display your saved image after decoding it as your are doing it currently.

Upvotes: 0

Related Questions