Vishwa Madushan Vishwa Madushan - 3 months ago 8
Android Question

How to use Intent to get external image and set as wallpaper

I used intent to open gallery of user's phone and now I need to set selected image as wallpaper for my activity.or set image to ImageView on my Activity.not the set as phone's wallpaper.
can somebody help me?
Here's the code I used so far.. i can select image.but nothing happens after that.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button chooseImg=(Button) findViewById(R.id.btnChooseImg);
chooseImg.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

Intent img=new Intent();
img.setType("image/*");
img.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser
(img, "Select Picture"),SELECT_PICTURE);

Object tag=v.getTag();
Integer rId=(Integer) tag;
img.putExtra("bgImage", rId);



try{
imgLayout=(ImageView) findViewById(R.id.bgImg1);


int imgId=img.getExtras().getInt("bgImage");
imgLayout.setBackgroundResource(imgId);

}
catch(Exception e){
Toast.makeText(getApplicationContext(), "nope", Toast.LENGTH_SHORT).show();
}

}
});

}

Answer

Implement onActivityResult like this

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

    if (requestCode == SELECT_PICTURE&& resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.yourimageview);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

For setting button background create a BitmapDrawable like this

BitmapDrawable bdrawable = new BitmapDrawable(context.getResources(),bitmap);

and for layout you can use setBackgroundDrawable method

Comments