I'm trying to add functionality to my app to allow users to select what image will be shown on a button by clicking the button and then selecting an image from their gallery. I've got the code below that allows selecting the image and displaying it on the button, but if the user exits the app it resets to the default image. I've been trying to figure out how to incorporate a DB to accomplish this, but haven't had much luck. Wondering if anybody has an example of this or thoughts on a different way to go about this? Thanks.
package com.example.imagepicker;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class ImagePicker extends Activity {
TextView textTargetUri;
ImageView targetImage;
ImageButton buttonLoadImage;
@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);
}
public void button1pressed(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
textTargetUri.setText(targetUri.toString());
Bitmap bitmapa;
Bitmap bitmapb;
try开发者_运维百科 {
bitmapa = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
bitmapb = Bitmap.createScaledBitmap (bitmapa,100,100,false);
buttonLoadImage.setImageBitmap(bitmapb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You can use sharedpreferences for it, which maintains the data at the application level. you can use sharedpreferences to store the info that what image was selected for your button last time in your application. refer to these links
http://marakana.com/forums/android/examples/63.html
http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html
精彩评论