0

So in mainactivity, I have an imageview changed to a picture from gallery. I want to change the image of an ImageButton in another activity into the picture that was selected.

1 Answer 1

1

MainActivity:

private static int RESULT_LOAD_IMAGE = 1;
private final String FILEPATH = "FilePath";

SharedPreferences prefs;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);        

    Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, 1);
        }
    });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        prefs.edit().putString(FILEPATH, picturePath);

    }


}

Then use SharedPreferences to get the imagePath and load the image in anotherActivity()

anotherActivity():

public class anotherActivity extends MainActivity{

private final String FILEPATH = "FinalPath";
String path;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstance);
    setContentView(R.layout.main);

    path = prefs.getString(FILEPATH, "");

    ImageButton imageButton = (ImageView) findViewById(R.id.imgBtn);
    imageButton.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(path)));

}

}
Sign up to request clarification or add additional context in comments.

1 Comment

BitmapDrawable is deprecated and prefs isn't shared I tried using setImageBitmap instead but its not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.