How to get image from camera from fragment in Android - java

In my code I got null on bitmap but Image created successfully and uri is fine but BitmapFactory.decodeFile() return null.
I used fragment below code:
public class CameraImage extends Fragment {
private static final int TAKE_PHOTO_CODE = 1888;
Button button;
private Uri fileUri1,fileUri;
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.camera_image,
container, false);
button = (Button) rootView.findViewById(R.id.button);
imageView = (ImageView) rootView.findViewById(R.id.imageview);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri1 = getOutputMediaFileUri();
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PHOTO_CODE) {
if (resultCode == Activity.RESULT_OK) {
BitmapFactory.Options options;
try {
Bitmap bitmap = BitmapFactory.decodeFile(pathname);
showDialog(bitmap, 1);
} catch (OutOfMemoryError e) {
try {
options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(pathname, options);
imageView.setImageBitmap(bitmap);
} catch (Exception e2) {
Log.e("Camera", "" + e2 + " " + e);
}
}
}
}
} }
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(MyApplication.getAppContext().getFilesDir().getAbsolutePath()),
IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
try {
mediaFile = File.createTempFile(
"IMG_" + timeStamp,
".jpg",
mediaStorageDir
);
} catch (Exception e) {
Log.e("Camera", "" + e);
mediaFile = new File(mediaStorageDir.getPath() + File.separator
, "IMG_" + timeStamp + ".jpg");
}
return mediaFile;
}
In above code I got null on bitmap in onActivityResult but I got uri from this image is present at that location.

there are two types of image we can get via camera:
1) thumbnail image by using below code in onActivityResult:
Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.i(TAG, "" + photo + " / " + data.getExtras().get("data") + " / " + data.getData());
showDialog(photo, 1);
2) full quality immage by using below code in onActivityResult:
BitmapFactory.Options options;
options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(pathname, options);
showDialog(bitmap, 1);
3) use third party easy and comfortable:
compile 'com.mindorks:paracamera:0.2.2'
paracamera github

I solved my question:
by changing cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
to
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri1);

Related

In Android studio , in my app the image is not getting replaced with the bitmap

In Android studio , in my app the image is not getting replaced with the bitmap I create,the path is correct but the ic_action_android is not getting replaced with my fresh captured image.
In OnCreate:
btOpen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
//Open Camera
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!=null)
{
File imageFile= null;
try{
imageFile = getImageFile();
}catch(IOException e){
Toast.makeText(getApplicationContext(), "get image file failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if(imageFile != null)
{
Uri imageUri= FileProvider.getUriForFile(MainActivity.this,"com.example.android.provider",imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(cameraIntent,IMAGE_REQUEST);
}
else
{
Toast.makeText(getApplicationContext(), "Imagefile is null", Toast.LENGTH_SHORT).show();
}
}
//startActivityForResult(intent,100);
}
});
private File getImageFile()throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageName="jpg_"+timeStamp+"_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageName,".jpg",storageDir);
currentImagePath= imageFile.getAbsolutePath();
return imageFile;
}
The on Activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView= new ImageView(MainActivity.this);
imageView.setImageResource(R.drawable.ic_action_android);
addView(imageView,1000,1000);
Log.i(TAG, "The image path is " + currentImagePath);
final Bitmap mBitmap= BitmapFactory.decodeFile(getIntent().getStringExtra(currentImagePath));
if (requestCode == 100) {
//Get Capture Image
// Bitmap captureImage = (Bitmap) data.getExtras().get("data");
//Set Captue Image to ImageView
imageView.setImageBitmap(mBitmap);
// imageView.setImageBitmap(captureImage);
}
imageView.setImageBitmap(mBitmap); this line is not working so to say.

OnActivityResult: Uri and getData is a null object during capture a photo

I have a problem with Uri object. User should take a photo and next this is sending to Firebase Storage. But sth is wrong with onActivityResult.
I read a lot of topics (https://developer.android.com/training/camera/photobasics.html, StackOverFlow too) but nothing works with this code.
There is an error:
Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
Below is a code:
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
}
As I checked, data (Intent) in onActivityResult is equal to NULL, so uri is null as well.
So, how can I resolve this challenge and make it usable? Should I use a Bitmap to have an access to a photo?
Could someone help me to resolve this situation?
Regards
I figured out with my question.
It works at now.
private ProgressDialog mProgress;
private Button mUploadBtn;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAMERA_REQUEST_CODE);
}
});
}
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
Always create your file and store the captured image using the path as follows
File photoFile = null;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
});
}
private File createImageFile() throws IOException {
// Create an image mSelectedFile name
String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return file;
}
Then use this file "photoFile" and use it as needed in onActivityResult.
I faced the same problem before so i made sure that i check everything i can check when onActivityResult is called below is my code.
First i use this intent to capture image
File photoFile;
URI uri;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = Create_ImageFile();
}
catch (Exception e)
{
Log.e("file", e.toString());
}
if (photoFile != null)
{
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
}
}
startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
try
{
Uri selectedImageURI = null;
ByteArrayOutputStream bos;
Bitmap bitmap = null;
int orientation;
ExifInterface exif = null;
FileOutputStream fos = null;
bos = new ByteArrayOutputStream();
try
{
uri=imageReturnedIntent.getData();
selectedImageURI = imageReturnedIntent.getData();
bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
}
catch (Exception e)
{
e.printStackTrace();
}
if(bitmap==null)
{
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
exif = new ExifInterface(photoFile.getAbsolutePath());
fos = new FileOutputStream(photoFile.getAbsolutePath());
}
if(bitmap==null)
{
String imagePath = getPathGalleryImage(imageReturnedIntent);
bitmap = BitmapFactory.decodeFile(imagePath);
exif = new ExifInterface(imagePath);
fos = new FileOutputStream(imagePath);
}
Log.e("PhotoFile",photoFile.getAbsolutePath());
// Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
//bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation ="+orientation);
//exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
//m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else
{
m.postRotate(0);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
//CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
userProfileIMG.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
private String getPathGalleryImage(Intent imageURI)
{
Uri selectedImage = imageURI.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 imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
/**
* When image is returned we get its real path
**/
private String GetRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private File Create_ImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
return image;
}
after this process i always ended having a bitmap to use it as i want.
For Get Actual Image predefined path of Captured Image using
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
After Captured Image you can get Captured Image on path which is set in cameraIntent. If you don't Want to set predefined path then check Intent data.
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
}
else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex)
{}}

Taking a picture via camera and sending it to server in bytearray

I am working on an Andorid application in which I would like the user to take a picture and then to save it I am sending it over to the server. Now, I am sending the picture as a byte-array to the server. When I try to save the byte-array to a file as a PNG file, and then try to open the file, the image-viewer complains that the PNG has errors and cannot be displayed. The PNG file size was 122Kb.
When I tried to use Scalr library to resize the image, it says the image source cannot be null. Directly saving the byte-array is causing a corrupt PNG. How should I convert and send the file properly to server, so there are no errors.
Here is the code for camera which I am using and sending it over.
public class AddPhotoForUser extends DrawerLoader {
private static final int CAMERA_PIC_REQUEST = 22;
Button BtnSelectImage;
private ImageView ImgPhoto;
private static volatile Bitmap photo;
private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();
final PersonServiceImpl personService = new PersonServiceImpl();
private String[] navMenuTitles;
private TypedArray navMenuIcons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_user_photo);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.INVISIBLE);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
uploadImage();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
startActivity(intent);
finish();
}
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(AddPhotoForUser.this, Login.class);
startActivity(intent);
finish();
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
try {
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode == RESULT_OK) {
try {
photo = (Bitmap) data.getExtras().get("data");
if (!(photo == null)) {
ImgPhoto.setImageBitmap(photo);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void uploadImage() {
if (!(photo == null)) {
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
personService.addUserProfilePhoto(byteArray);
}
}
}
Here is the server side code to save the image to disk :
#Override
public Boolean updateProfilePhoto(byte[] photo) {
Person person = getCurrentlyAuthenticatedPerson();
try{
InputStream in = new ByteArrayInputStream(photo);
BufferedImage image = ImageIO.read(in);
image = Scalr.resize(image, Scalr.Method.QUALITY, 100, 100);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
baos.flush();
File file = new File(userImagePath);
if (file.exists() && file.isDirectory()) {
OutputStream outputStream = new FileOutputStream(new File(userImagePath + person.getUserId()+".png"));
outputStream.write(baos.toByteArray());
outputStream.close();
} else {
File file1 = new File(userImagePath+person.getUserId()+".png");
if (file1.exists()) {
try {
OutputStream outputStream = new FileOutputStream(file1);
outputStream.write(baos.toByteArray());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
boolean result = file1.createNewFile();
System.out.println("Result of file1 creation is "+result);
OutputStream outputStream = new FileOutputStream(file1);
outputStream.write(baos.toByteArray());
outputStream.close();
}
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
If I don't use the Scalr library, there are no errors, but its a corrupt file. Here is the Scalr error log :
java.lang.IllegalArgumentException: src cannot be null
at org.imgscalr.Scalr.resize(Scalr.java:1564)
at org.imgscalr.Scalr.resize(Scalr.java:1415)
at com.journaldev.spring.service.PersonServiceImpl.updateProfilePhoto(PersonServiceImpl.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy51.updateProfilePhoto(Unknown Source)
at com.journaldev.spring.Controller.PersonController.addProfilePhotoForUser(PersonController.java:100)
Any help would be nice. Thanks a lot. :-)
Updated code
public class AddPhotoForUser extends DrawerLoader {
Button BtnSelectImage;
private ImageView ImgPhoto;
private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();
final PersonServiceImpl personService = new PersonServiceImpl();
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
Bitmap reducedSizeBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_user_photo);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.INVISIBLE);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
uploadImage();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
startActivity(intent);
finish();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 12000000; // 12MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(AddPhotoForUser.this, Login.class);
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage() {
if(!(reducedSizeBitmap == null)){
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.personService.addUserProfilePhoto(byteArray);
}
}
}
If you use Bundle extras = data.getExtras(); in your onActivityResult() then it will return thumbnail image not actual image.
Here is code I have used for Capturing and Saving Camera Image then display it to ImageView. You can use according to your need.
You have to save Camera image to specific location then fetch from that location then convert it to byte-array.
Here is method for opening capturing camera image activity.
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
then your onActivityResult() method should be like this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
EDIT:
Here is method for uploading image to server.
/**
* Upload Image to server
*
* #param file image to be saved
* #param compressorQuality quality of image
* #return path of uploaded image in server
*/
private String uploadImage(Bitmap file, int compressorQuality) {
String final_upload_filename = "demo_image.png";
String response = null;
HttpURLConnection conn = null;
try {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------14737809831466499882746641449";
URL url = new URL("image_upload_url");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", final_upload_filename);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes(lineEnd);
file.compress(CompressFormat.PNG, compressorQuality, dos);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
byte[] bytes = new byte[1024];
while ((bytesRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytesRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
response = new String(bytesReceived);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
You need to make upload script in backend server to store image data in particular folder.
I hope it helps!
At first you need to create a file and save image on it and here's a code.
//method to save image in internal or external storage
private void storeImage(Bitmap image,String imageName) {
File pictureFile = getOutputMediaFile(imageName);
if (pictureFile == null) {
Log.d(TAG,"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
//method to create file to save image on it
private File getOutputMediaFile(String imageName){
//create folder with name FoursquareAPI
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/FoursquareAPI");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
File mediaFile;
String mImageName= imageName +".png";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}

Create folder and store Image by camera

please read my code ask solution how to create folder
public class CameraActivity extends ActionBarActivity {
private static final int ACTION_TAKE_IMAGE = 1;
Button btnImage;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView = (ImageView)findViewById(R.id.imageView);
btnImage= (Button) findViewById(R.id.buttonCapture);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takeVideoIntent, ACTION_TAKE_IMAGE);
}
});
}
#onActivityResult start
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
try
{
AssetFileDescriptor imageAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = imageAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"/Vipul/RecordImage/");
if (!root.exists()) {
System.out.println("No directory");
root.mkdirs();
}
File file;
file=new File(root,"IMG_"+System.currentTimeMillis()+".jpg" );
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if(requestCode == ACTION_TAKE_IMAGE && resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
Bitmap imageBitmap = (Bitmap) bundle.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
}
this code work 2.3 capture Image but work and not create folder not store in my specific folder please ask your answer
UPDATE
//declare
int num = 0;
//.....//
//*onclik button
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Create folder
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "Myfolder");
imagesFolder.mkdirs();
//Asign name for image
File image = new File(imagesFolder, "Pic" + (num +1) + ".png");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//launch camera app with result code (forResult)
startActivityForResult(cameraIntent, 1);
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK)
{
//create bitmap with image
Bitmap bMap = BitmapFactory.decodeFile(
Environment.getExternalStorageDirectory() +
"/Myfolder/" + "Pic" + num + ".png");
//Add bitmap to ImageView
//Show on screen
imageView.setImageBitmap(bMap);
}
To use different name for image everytime you can use method getTimeInMillis() as Calendar mCalendar = Calendar.getInstance();
String n = ""+mCalendar.getTimeInMillis();
String fname = "Pic-" + n.substring(5) + ".png";
//Asign name for image
File image = new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);
try this code
public class CameraActivity extends ActionBarActivity {
// private static final int ACTION_TAKE_IMAGE = 1;
Button btnImage;
ImageView imageView;
File image;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView = (ImageView) findViewById(R.id.imageView);
btnImage = (Button) findViewById(R.id.buttonCapture);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Create folder
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "Vipul/image");
imagesFolder.mkdirs();
//Asign name for image
String fname = "Pic-" + System.currentTimeMillis() + ".png";
image= new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//launch camera app with result code (forResult)
startActivityForResult(cameraIntent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
}
}
}
final solution

Implementing fix on Out of Memory Error

In my widget, I have an imageView that collect an image from the user gallery and then sets that image up as the background in another activity. It works fine, but when I try to add an image file that is too big (such as an image from the camera) or upload many image files, I get an "out of memory" error. After looking around stackoverflow for a while, I noticed that everyone pretty much used the basic method of:
public static Bitmap decodeSampleImage(File f, int width, int height) {
try {
System.gc(); // First of all free some memory
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int requiredWidth = width;
final int requiredHeight = height;
// Find the scale value (as a power of 2)
int sampleScaleSize = 1;
while (o.outWidth / sampleScaleSize / 2 >= requiredWidth && o.outHeight / sampleScaleSize / 2 >= requiredHeight)
sampleScaleSize *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = sampleScaleSize;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (Exception e) {
Log.d(TAG, e.getMessage()); // We don't want the application to just throw an exception
}
return null;
}
I also noticed that people have recycled unused bitmaps as well. I understand how this works but I don't know where I should put it in my coding.
Here are my two classes (Personalize.java where the imageView to collect the background is. It has the imageView and two buttons (one for choosing an image from the gallery where it then displays that image into the imageView and the other to then set that image as the background).
First here is Personalize.java:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Personalize extends Activity implements View.OnClickListener {
Button button;
ImageView image; //the imageview for setting the background
ImageView image2; //the imageview for setting the icon (not focusing on)
Button btnChangeImage;
Button btnChangeImageForIcon;
Button btnSetBackground;
private static final int SELECT_PICTURE = 1;
private static final int SELECT_PICTURE_2 = 2;
private String selectedImagePath;
Bitmap background;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalize);
image = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2Icon);
Button btnChangeImage = (Button) findViewById(R.id.btnChangeImage);
btnChangeImage.setOnClickListener(this);
Button btnChangeImageForIcon = (Button) findViewById(R.id.btnChangeImageForIcon);
btnChangeImageForIcon.setOnClickListener(this);
Button btnSetBackground = (Button) findViewById(R.id.btnSetBackground);
btnSetBackground.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnChangeImage:
launchImageChooser();
break;
case R.id.btnChangeImageForIcon:
launchImageChooser();
break;
case R.id.btnSetBackground:
setBackgroundImageInDragAndDrop();
break;
}
}
private void setBackgroundImageInDragAndDrop() {
Log.d("Personalize", "setBackgroundImageInDragAndDrop() called");
Intent i = getIntent();
//Convert bitmap to byte array to send back to activity
// See: http://stackoverflow.com/questions/11010386/send-bitmap-using-intent-android
ByteArrayOutputStream stream = new ByteArrayOutputStream();
background.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray = stream.toByteArray();
i.putExtra("myBackgroundBitmap", byteArray);
setResult(RESULT_OK, i);
finish();
}
private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String imagePath = cursor.getString(column_index);
if(cursor != null) {
cursor.close();
}
return imagePath;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
background = getAndDecodeImage(selectedImagePath);
if(background != null){
image.setImageBitmap(background);
}
} else if (requestCode == SELECT_PICTURE_2)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap b2 = getAndDecodeImage(selectedImagePath);
if(b2 != null){
image2.setImageBitmap(b2);
}
}
}
}
private Bitmap getAndDecodeImage(String selectedImagePath){
try {
Log.d("Personalize", "selectedImagePath: " + selectedImagePath);
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
if (fileis != null)
{
fileis.close();
}
if (bufferedstream != null)
{
bufferedstream.close();
}
return bMap;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = this.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
return false;
}
}
}
Then here is my Drag_and_Drop_App.java (snippet of important parts -- collects bitmap and sets as background):
package com.example.awesomefilebuilderwidget;
IMPORTS
public class Drag_and_Drop_App extends Activity {
private static final int SET_BACKGROUND = 10;
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public AppInfoAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// import buttons
Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);
Button btnLinkToPersonalize = (Button) findViewById(R.id.btnLinkToPersonalize);
// Link to Personalize Screen
btnLinkToPersonalize.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Personalize.class);
startActivityForResult(i, SET_BACKGROUND);
}
});
}
public Bitmap getThumbnail(String filename) {
Bitmap thumbnail = null;
try {
File filePath = this.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
return thumbnail;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Drag_and_Drop_App", "requestCode: " + requestCode + ", resultCode: " + resultCode);
if(requestCode == SET_BACKGROUND && resultCode == RESULT_OK){
byte[] byteArray = data.getByteArrayExtra("myBackgroundBitmap");
Bitmap myBackground = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
setBackgroundImage(myBackground);
}
}
#SuppressLint("NewApi")
private void setBackgroundImage(Bitmap bitmap) {
RelativeLayout yourBackgroundView = (RelativeLayout) findViewById(R.id.rl_drag_and_drop_app);
Drawable d = new BitmapDrawable(getResources(), bitmap);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
yourBackgroundView.setBackgroundDrawable(d);
} else {
yourBackgroundView.setBackground(d);
}
}
}
So where could I implement that coding and where could I also get rid of other unused bitmaps in memory? (recycle them?)

Categories