Skip to content Skip to sidebar Skip to footer

Upload Image And Set It As Background Android

I am trying to upload an image and set it as a background but I'm having no luck. So the uploading is working fine but when I try to set the image as a background It does not work.

Solution 1:

1) setBackground fails due to large image size, try to scale it down before setting:

 Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, false); //set the w x h as you want
 BitmapDrawable bit_background = new BitmapDrawable(getResources(), scaledBitmap);
 prof_bg.setVisibility(View.VISIBLE);
 prof_bg.setBackground(bit_background);

2) Save the targetUri string in SharedPreferences and retrieve it to set when activity begins.


Solution 2:

OnActivityResult(), you must ensure that the file path is correct. This is what I do. Maybe you can give a try.

Uri targetUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

Cursor cursor = mContext.getContentResolver().query(targetUri,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();

Once you get picturePath, you can save it into SharedPreference so that you can check and retrieve it if there is any. So you don't have to pick the picture again.

// to set the background image
BitmapDrawable bb = new BitmapDrawable (null, BitmapFactory.decodeFile(picturePath));
(findViewById(R.id.bg_image)).setImageDrawable(bb);

Post a Comment for "Upload Image And Set It As Background Android"