1. Are you ready for the Galaxy S20? Here is everything we know so far!

Imagebutton and SharedPreferences

Discussion in 'Android Development' started by jdbeuerlein, Jun 1, 2011.

  1. jdbeuerlein

    jdbeuerlein Lurker
    Thread Starter

    For part of an app I'm working on, I want to allow the user to select what image will appear on a button by clicking the button. The image should then remain the same even if the app closes, unless the user goes through and picks another image.

    I've been trying to get it done using an imagebutton and sharedpreferences. I've got the app to where it will work sometimes, but about the third or fourth time I change the image the app fails.

    I'd appreciate any ideas on what I might be doing wrong or better ways to approach this. Thanks in advance.

    package com.example.imagepicker;

    import android.app.Activity;

    import android.content.Intent;

    import android.content.SharedPreferences;

    import android.net.Uri;

    import android.os.Bundle;

    import android.view.View;

    import android.widget.ImageButton;

    import android.widget.TextView;

    public class ImagePicker extends Activity {

    TextView textTargetUri;
    ImageButton buttonLoadImage;
    Uri uriSavedMem1;
    Uri targetUri;
    String strSavedMem1;
    SharedPreferences images;

    public void onCreate(Bundle savedInstanceState) {
    textTargetUri = (TextView)findViewById(R.id.targeturi);
    buttonLoadImage = (ImageButton)findViewById(R.id.Button01);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v){
    startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), SELECT_IMAGE);

    private void LoadPreferences(){
    images = getSharedPreferences("Images", MODE_PRIVATE);
    strSavedMem1 = images.getString("Image1", "");
    uriSavedMem1 = Uri.parse(strSavedMem1);
    private void SavePreferences(String key, String value){
    images = getSharedPreferences("Images", MODE_PRIVATE);
    SharedPreferences.Editor editor = images.edit();
    editor.putString(key, value);
    editor.commit(); }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
    targetUri = data.getData();
    SavePreferences("Image1", targetUri.toString());



Share This Page