Endi Tóth
Endi Tóth

Reputation: 221

Save image as string with SharedPreferences

I'm writing an app which in I have to save the state of the Activity. I have an ImageView and a Button on the screen. When I click on the Button the ImageView change the background image. My problem is when I stop the Activity and start it again the ImageView shows the first image. I converted my image into a String with Base64. Then I saved the string with SharedPreferences. After that i got it and decode again with Base64. I dont have any error message but it's not working. I copy my code and if anyone has an idea how to do it please response!

public static final String IMAGE = "Image";
public static final String DB_INIT = "DB_INIT";

Button button;
ImageView imageview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences sp = getApplicationContext().getSharedPreferences(
            DB_INIT, MODE_PRIVATE);
    String backimage = sp.getString(IMAGE, "res/drawable/my_image.png");

    button = (Button) findViewById(R.id.button1);
    imageview = (ImageView) findViewById(R.id.imageview);

    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            imageview.setBackgroundResource(R.drawable.szaz);
        }
    });
}
@Override
protected void onStop() {
    SharedPreferences sp = getApplicationContext().getSharedPreferences(
            DB_INIT, MODE_PRIVATE);
    SharedPreferences.Editor et = sp.edit();
    et.putString(IMAGE,"res/drawable/my_image.png");
    et.commit();
    super.onStop();
  }
}

Upvotes: 2

Views: 1633

Answers (0)

Related Questions