• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Imagebutton and SharedPreferences

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;
intSELECT_IMAGE;



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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);
}
});
LoadPreferences();
}



private void LoadPreferences(){
images = getSharedPreferences("Images", MODE_PRIVATE);
strSavedMem1 = images.getString("Image1", "");
uriSavedMem1 = Uri.parse(strSavedMem1);
buttonLoadImage.setImageURI(uriSavedMem1);
textTargetUri.setText(strSavedMem1);
}
private void SavePreferences(String key, String value){
images = getSharedPreferences("Images", MODE_PRIVATE);
SharedPreferences.Editor editor = images.edit();
editor.putString(key, value);
editor.commit(); }
@Override
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();
textTargetUri.setText(targetUri.toString());
buttonLoadImage.setImageURI(null);
buttonLoadImage.setImageURI(targetUri);
SavePreferences("Image1", targetUri.toString());
LoadPreferences();
}
}


}
 
Back
Top Bottom