How do I save the name after generating QR code - java

I am trying to make an app that generates QR Code.
It works well but there is no text when it is saved. People would be confused after saving a few codes because of no name on it.
If people generate QR code with "Wikipedia.com", I want it saved with the name of "Wikipedia.com" at the photo gallery. What should I do?
MainActivity
public class MainActivity extends AppCompatActivity {
private String inputValue;
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
private Bitmap bitmap;
private QRGEncoder qrgEncoder;
private ImageView qrImage;
private EditText edtValue;
private AppCompatActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = findViewById(R.id.qr_image);
edtValue = findViewById(R.id.edt_value);
activity = this;
/**Barcode Generator*/
findViewById(R.id.generate_barcode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
try {
bitmap = qrgEncoder.getBitmap();
qrImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else {
edtValue.setError(getResources().getString(R.string.value_required));
}
}
});
/**Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});
}
}

I tried your code and it works fine. The generated QR codes are saved as you want: QR-code-text.jpg
The only problem is the QRGSaver().save(...) is not compatible with Android10+.
Try to extend your onClickListener of save_barcode button as follows:
/*Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(v -> {
String filename = edtValue.getText().toString().trim();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Toast.makeText(activity, "Image Saved. Check your gallery.", Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});

Related

Gallery doesn't refresh using MediaScan

I have the following Java code which downloads an image from an URL.
I can see the image downloaded in the folder, but the image does not appear in gallery. Only if I restart phone, Samsung S7 with android 7, I can see images in gallery. What can I do to have the images in gallery in real time after I downloaded them?
public class DetailsImgActivity extends AppCompatActivity {
private static final String TAG = "DetailsImgActivity";
private ImageView imageViewPoze;
private Button buttonDownload;
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_img);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
// image url stored in imageID
final String imageId = getIntent().getStringExtra("ImageId");
imageViewPoze = findViewById(R.id.imageViewPozeC);
Picasso.get().load(imageId).into(imageViewPoze);
buttonDownload = findViewById(R.id.btn_Download_Img);
buttonDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
downloadFile(imageId);
}
});
}
private void downloadFile(String url) {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://firebasestorage.blabla.com/");
Retrofit retrofit = builder.build();
FileDownloadClient fileDownloadClient = retrofit.create(FileDownloadClient.class);
Call<ResponseBody> call = fileDownloadClient.downloadFile(url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
// if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
return null;
}
}.execute();
//after the image has been downloaded -refresh gallery
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "error");
}
});
}
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
String folder_main = Constants.dirName;
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), folder_main);
if (!f.exists()) {
f.mkdirs();
}
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM+"/"+ Constants.dirName)
+ File.separator + UUID.randomUUID()+".jpg");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
}
I used the follwing code, but If I don't reboot phone, I can't see the picture in gallery.
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**

App is crashing when we upload the image from gallery?

I am new in android so, if you found any mistake please tell me.Now come to the point what i got the problem we click on image view then one popup will come and choose from where you want to upload the image so when we click on gallery then.
mProfileImageView.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
new AlertDialog.Builder(ProfileActivity.this)
.setTitle("Profile Picture")
.setMessage("change your profile picture with")
.setPositiveButton(R.string.capture_image, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// continue with delete
captureImage();
}
})
*//*.setNegativeButton(R.string.choose_image, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
chooseImage();
}
})*//*
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
public void chooseImage() {
try {
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, IMAGE_QUALITY_LOW);
i.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, 0);
i.putExtra(MediaStore.EXTRA_SIZE_LIMIT, IMAGE_MAX_SIZE);
i.setType("image/*");
//i.setAction(Intent.ACTION_GET_CONTENT);
/*i.putExtra("crop", "true");
i.putExtra("aspectX", 0);
i.putExtra("aspectY", 0);
i.putExtra("outputX", 400);
i.putExtra("outputY", 400);
i.putExtra("return-data", true);*/
startActivityForResult(Intent.createChooser(i, "Complete action using"), GALLERY_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Oops - your device doesn't have gallery!";
Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_LONG).show();
}
}
When we are scrollingG 10-20 gallery images and going for upload at that time it's crashing i don't know why?
try this:
java code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int SELECT_PICTURE = 100;
private static final String TAG = "MainActivity";
CoordinatorLayout coordinatorLayout;
FloatingActionButton btnSelectImage;
AppCompatImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find the views...
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
btnSelectImage = (FloatingActionButton) findViewById(R.id.btnSelectImage);
imgView = (AppCompatImageView) findViewById(R.id.imgView);
btnSelectImage.setOnClickListener(this);
}
/* Choose an image from Gallery */
void openImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
imgView.setImageURI(selectedImageUri);
}
}
}
}
/* Get the real path from the URI */
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
#Override
public void onClick(View v) {
openImageChooser();
}
}
Add Permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.AppCompatImageView
android:id="#+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/activity_horizontal_margin" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/btnSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_menu_gallery" />
</android.support.design.widget.CoordinatorLayout>
You are receiving an OutOfMemoryException since you are talking about several images. Here are your options:
Request a larger heap from the virtual machine by adding the following line into your AndroidManifest.xml in the application section: android:largeHeap="true"
Try to use images as small as possible for your gallery. Remeber: each image is stored uncompressed into your applications heap
Recycle images that are not visible at the moment using Bitmap.recycle() to free new memory.
Try this java code it works. I used it recently in my android app
Pop up
PopupWindow popup;
private void initiatePopupWindow() {
// TODO Auto-generated method stub
try {
LayoutInflater inflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.change_profileimg, null);
popup = new PopupWindow(layout, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
Button imagefromgallery = (Button) layout
.findViewById(R.id.imagefromgallery);
RelativeLayout relPopup = (RelativeLayout) layout.findViewById(R.id.relativeLayoutMainPopup);
Button captureimage = (Button) layout
.findViewById(R.id.captureimage);
imagefromgallery.setTypeface(Typeface.createFromAsset(getAssets(),
"fonts/OpenSans-Regular.ttf"));
captureimage.setTypeface(Typeface.createFromAsset(getAssets(),
"fonts/OpenSans-Regular.ttf"));
imagefromgallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
galleryPick();
popup.dismiss();
}
});
captureimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// takePhoto();
callCameraApp();
popup.dismiss();
}
});
relPopup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
}
});
popup.setOutsideTouchable(true);
popup.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
popup.dismiss();
return true;
}
return false;
}
});
popup.showAtLocation(layout, Gravity.BOTTOM, 0, 0);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Gallery pick
private void galleryPick() {
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gintent, "Select Picture"), PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
Call camera app
private void callCameraApp() {
Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
String fileName = "new-photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, fileName);
values.put(ImageColumns.DESCRIPTION, "Image captured by camera");
// imageUri is the current activity attribute, define and save it for
// later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
fileName = getPath(imageUri);
} catch (Exception e) {
// TODO: handle exception
}
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, PICK_Camera_IMAGE1);
}
then to get the bitmap
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"XYZ_");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("errorrr", "Oops! Failed create "
+ "XYZ_" + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
return mediaFile;
}
String filePath;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImageUri = null;
Uri selectedImagepicUri = null;
filePath = null;
switch (requestCode) {
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImageUri = imageUri;
/*
* Bitmap mPic = (Bitmap) data.getExtras().get("data");
* selectedImageUri =
* Uri.parse(MediaStore.Images.Media.insertImage
* (getContentResolver(), mPic,
* getResources().getString(R.string.app_name),
* Long.toString(System.currentTimeMillis())));
*/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
}
break;
case PICK_Camera_IMAGE1:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImagepicUri = imageUri;
/*
* Bitmap mPic = (Bitmap) data.getExtras().get("data");
* selectedImageUri =
* Uri.parse(MediaStore.Images.Media.insertImage
* (getContentResolver(), mPic,
* getResources().getString(R.string.app_name),
* Long.toString(System.currentTimeMillis())));
*/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
}
break;
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
selectedImagepicUri = data.getData();
}
}
if (selectedImagepicUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImagepicUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImagepicUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile1(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
if (selectedImageUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 512;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
/**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/
if (bitmap == null) {
Toast.makeText(getApplicationContext(), "Please select image",
Toast.LENGTH_SHORT).show();
} else {
ivr.setImageBitmap(bitmap);
ivrIn.setImageBitmap(bitmap);
// new ImageGalleryTask().execute();
}
}
public void decodeFile1(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 512;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
/**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/
if (bitmap == null) {
Toast.makeText(getApplicationContext(), "Please select image",
Toast.LENGTH_SHORT).show();
} else {
ivr.setImageBitmap(bitmap);
ivrIn.setImageBitmap(bitmap);
// new ImageGalleryTask().execute();
}
}
Async task to upload image
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressDialog = new ProgressDialog(Profile.this);
//progressDialog.setTitle("Fetching data");
progressDialog.setMessage("Uploading profile pic, Please Wait....");
progressDialog.show();
progressDialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
System.out.println("progress update "+progress[0]);
// progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
// progressBar.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
int count;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
URL url = new URL("url");
System.out.println("url "+url);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + filePath + "\"" + lineEnd);
Log.e("chhuuuh", filePath + System.currentTimeMillis());
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
responseString = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
InputStream is = null;
try {
is = connection.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
return sb.toString();
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
is.close();
}
}
}
catch (Exception ex)
{
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
String result1 = result;
Log.e("respons form server", "response from server: " + result);
if(progressDialog.isShowing())
{
progressDialog.dismiss();
}
try {
JSONObject json = new JSONObject(result);
int response = json.getInt("status_code");
if(response == 1)
{
if (result1.contains("null")) {
Toast.makeText(getApplicationContext(), "You didn't change the image, please choose an image from gallery or click from the camera.", 2000).show();
} else {
JSONObject arr = json.getJSONObject("details");
String erer = arr.getString("error");
String message = arr.getString("message");
Toast.makeText(getApplicationContext(), message, 1000).show();
}
}
else
{
showAlert("Error Uploading Image, Please try again!!!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPostExecute(result);
}
}
get the correct path
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
Permissions for 6.0 and above versions
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d("", "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initialize the map with both permissions
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CALL_PHONE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Log.d("", " permission granted");
// process the normal flow
//else any one or both the permissions are not granted
} else {
Log.d("", "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
// shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
showDialogOK("This app have camera functionality so Camera and Write External Storage Permission required for this app",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
Toast.makeText(getApplicationContext(), "Please go to settings and enable permissions.", 2000).show();
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
private boolean checkAndRequestPermissions() {
int permissionCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int permissionWriteExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionCallPhone = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
List<String> listPermissionsNeeded = new ArrayList<String>();
if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionCallPhone != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
I know this code is too long to read but this is exactly what you want

Out of memory on a 65536016-byte allocation using glide library android

I have tried many things to handle this error. I was facing the same issue when i was using picasso before glide. When ever i click on "change photo" and select a photo from gallery or camera etc and want to set that selected image in the "Update Activity" in the image view. It throws out of memory exception. I am resizing the image size to 500x500 and compress it then trying to set it in the image view but it stills goes out of memory.I guess the problem is that i am not freeing this memory allocated but i searched but did not get any idea. Thanks in advance.
package com.donateblood.blooddonation;
/**
* Created by YouCaf Iqbal on 6/29/2016.
*/
public class UpdateActivity extends AppCompatActivity {
#InjectView(R.id.image)
ImageView _USERImage;
#InjectView(R.id.input_name)
EditText _nameText;
#InjectView(R.id.btnchangephoto)
Button changePhoto;
#InjectView(R.id.input_password)
EditText _passwordText;
#InjectView(R.id.input_number)
TextView _numText;
public static boolean UpdatingPhoto = false;
public String encodedPhotoString = null;
public String ChangedName = null;
public String ChangedPassword = null;
public String ChangedContactNo = null;
HashMap<String, String> ThingsTobeUpdated = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.updateactivity);
ButterKnife.inject(this);
}catch (OutOfMemoryError e){
Toast.makeText(getBaseContext(), "Sorry,Something went wrong, try again", Toast.LENGTH_SHORT).show();
}
ThingsTobeUpdated = new HashMap<>();
CheckImage();
changePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdatingPhoto = true;
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UpdateActivity.this.finish();
}
});
}
public void CheckImage() {
if (CroppingActivity.newImage != null) {
Drawable drawable = _USERImage.getDrawable();
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
bitmap.recycle();
CroppingActivity.newImage = getResizedBitmap(CroppingActivity.newImage,500,500);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
CroppingActivity.newImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Uri uri = getImageUri(CroppingActivity.newImage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Glide.with(UpdateActivity.this).load(file).override(400,400).placeholder(R.drawable.user).error(R.drawable.error)
.centerCrop().crossFade().bitmapTransform(new CropCircleTransformation(UpdateActivity.this)).into(_USERImage);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
} else {
Glide.with(UpdateActivity.this).load(getImageURL()).override(400,400).placeholder(R.drawable.user).error(R.drawable.error)
.centerCrop().crossFade().bitmapTransform(new CropCircleTransformation(UpdateActivity.this)).into(_USERImage);
}
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UpdateActivity.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(UpdateActivity.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getImageURL(){
return "http://abdulbasit.website/blood_app/images/"+LoginActivity.ImageofLoggedINUser;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_update, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String ChangesHappened = "no";
if (item.getItemId() == R.id.done_update) {
// start updating process
if(_nameText.getText().toString().equals("")){
ChangedName = null;
}else {
ChangedName = _nameText.getText().toString();
ChangesHappened = "yes";
}
if(_passwordText.getText().toString().equals("")){
ChangedPassword = null;
}else {
ChangedPassword = _passwordText.getText().toString();
ChangesHappened = "yes";
}
if(_numText.getText().toString().equals("")){
ChangedContactNo = null;
}else {
ChangedContactNo = _numText.getText().toString();
ChangesHappened = "yes";
}
if(encodedPhotoString!=null){
ChangesHappened = "yes";
}
if(ChangesHappened=="yes"){
StartUpdate();
return true;
}else {
Toast.makeText(getBaseContext(), "Nothing to update", Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
private void StartUpdate() {
ThingsTobeUpdated.put("email", LoginActivity.EmailofLoggedInUser);
if (encodedPhotoString != null) {
ThingsTobeUpdated.put("image", encodedPhotoString);
}
if (ChangedName != null) {
ThingsTobeUpdated.put("name", ChangedName);
}
if (ChangedPassword != null) {
ThingsTobeUpdated.put("password", ChangedPassword);
}
if (ChangedContactNo != null) {
ThingsTobeUpdated.put("contact", ChangedContactNo);
}
UpdateAsync updatestart = new UpdateAsync();
updatestart.execute();
}
public class UpdateAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
JSONObject json = null;
#Override
protected Void doInBackground(Void... voids) {
json = new HttpCall().postForJSON("http://abdulbasit.website/blood_app/UpdateProfile.php", ThingsTobeUpdated);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateActivity.this);
pDialog.setMessage("Updating profile...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if (json != null) {
Toast.makeText(getBaseContext(), "Profile updated, Login Again to see changes", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getBaseContext(), "Error updating profile. Try Again", Toast.LENGTH_LONG).show();
}
}
}
}
public class CroppingActivity extends AppCompatActivity {
private CropImageView mCropImageView;
public static Bitmap finalImage = null;
public static Bitmap newImage = null;
private Uri mCropImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 400);
}
public void onSetImageClick(View view) {
if(UpdateActivity.UpdatingPhoto){
newImage = mCropImageView.getCroppedImage(400, 400);
try {
Intent intent = new Intent(getApplicationContext(), UpdateActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else {
finalImage = mCropImageView.getCroppedImage(400, 400);
try {
Intent intent = new Intent(getApplicationContext(), UploadImage.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(400, 400);
if (cropped != null)
mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
#Override
public void onBackPressed() {
UpdateActivity.UpdatingPhoto = false;
super.onBackPressed();
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCropImageView.setImageUriAsync(mCropImageUri);
} else {
Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list (android) so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null && data.getData() != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
/**
* Test if we can open the given Android URI to test if permission required error is thrown.<br>
*/
public boolean isUriRequiresPermissions(Uri uri) {
try {
ContentResolver resolver = getContentResolver();
InputStream stream = resolver.openInputStream(uri);
stream.close();
return false;
} catch (FileNotFoundException e) {
if (e.getCause() instanceof ErrnoException) {
return true;
}
} catch (Exception e) {
}
return false;
}
}
can't open /data/misc/app_oom.hprof: Permission denied
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm-heap: hprofDumpHeap failed with result: -1
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm-heap: After hprofDumpHeap for process
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm: Out of memory: Heap Size=76760KB, Allocated=13818KB, Limit=98304KB, Proc Limit=98304KB
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm: Extra info: Footprint=76760KB, Allowed Footprint=76760KB, Trimmed=16KB
07-04 16:25:41.436 23278-23278/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.donateblood.blooddonation, PID: 23278
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donateblood.blooddonation/com.donateblood.blooddonation.UpdateActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653) at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donateblood.blooddonation.UpdateActivity.CheckImage(UpdateActivity.java:93)
at com.donateblood.blooddonation.UpdateActivity.onCreate(UpdateActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)

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?)

How to save overlay with camera preview in android?

I am able to place a overlay over a live camera feed, but I also need to save the image captured by camera with that overlay.
Here is the code of my MainActivity.class file :
public class MainActivity extends Activity {
private Button takePhoto, pickPhoto;
private FrameLayout preview;
private CameraSurfaceView cameraSurfaceView;
private static final int SELECT_PICTURE_ACTIVITY_RESULT_CODE = 1;
private static final int CAMERA_PIC_REQUEST = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto = (Button) findViewById(R.id.btn_takephoto);
pickPhoto = (Button) findViewById(R.id.btn_pickPhoto);
preview = (FrameLayout) findViewById(R.id.frameLayout1);
takePhoto.setOnClickListener(clickListener);
pickPhoto.setOnClickListener(clickListener);
cameraSurfaceView = new CameraSurfaceView(MainActivity.this);
preview.addView(cameraSurfaceView);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.equals(takePhoto)) {
Camera camera = cameraSurfaceView.getCamera();
camera.takePicture(null, null, new HandlePictureStorage());
} else if (v.equals(pickPhoto)) {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*"); // to pick only images
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(photoPickerIntent,
SELECT_PICTURE_ACTIVITY_RESULT_CODE);
}
}
};
private class HandlePictureStorage implements PictureCallback {
#Override
public void onPictureTaken(byte[] picture, Camera camera) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "CameraTest" + date + ".jpg";
String filename = Environment.getExternalStorageDirectory()
+ File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(picture);
fos.close();
Toast.makeText(getApplicationContext(),
"New Image saved:" + photoFile, Toast.LENGTH_LONG)
.show();
} catch (Exception error) {
Log.d("Error",
"File" + filename + "not saved: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Image could not be saved.", Toast.LENGTH_LONG).show();
}
Intent newInt = new Intent(MainActivity.this, AddImageOverlay.class);
newInt.putExtra(Constant.BitmatpByteArray, filename);
startActivity(newInt);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_PICTURE_ACTIVITY_RESULT_CODE:
Uri selectedImageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), selectedImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Photo Picked",
Toast.LENGTH_SHORT).show();
// deal with it
break;
default:
// deal with it
break;
}
}
}
}
And the code of CameraSurfaceView.java :
public class CameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
public CameraSurfaceView(Context context) {
super(context);
// Initiate the Surface Holder properly
this.holder = this.getHolder();
this.holder.addCallback(this);
this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder h, int format, int width,
int height) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(width, height);
camera.setParameters(parameters);
camera.startPreview();
h.getSurface().setLayer(R.drawable.ic_launcher);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Open the Camera in preview mode
this.camera = Camera.open();
this.camera.setPreviewDisplay(this.holder);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when replaced with a new screen
// Always make sure to release the Camera instance
camera.stopPreview();
camera.release();
camera = null;
}
public Camera getCamera() {
return this.camera;
}
}

Categories