App is crashing when we upload the image from gallery? - java

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

Related

Upload image from camera and gallery to firebase

As the title says, I am trying to upload images from both camera and gallery to firebase. But I have problems in both.
When I try to upload my image from the camera I get:
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
Even though my firebase rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
But when I try using the gallery I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.varroxsystems.plant.newPlant.Fileuploader(newPlant.java:192)
at com.varroxsystems.plant.newPlant.access$100(newPlant.java:57)
at com.varroxsystems.plant.newPlant$2.onClick(newPlant.java:162)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
And I get no data in the firebase real time database nor in the firebase storage.
But I use this exact code on another application and it works just fine.
Does anyone know what am I doing wrong?
Code:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plants = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plants.setPlname(pname);
plants.setPldate(pdate);
plants.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plants);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
}
}
private String getExtension(Uri uri)
{
ContentResolver cr=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void askFileReadPermission() {
if (ContextCompat.checkSelfPermission(newPlant.this,
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.CAMERA) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.CAMERA)||ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
alert();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile && writeExternalFile)
{
alert();
} else {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
private void alert() {
new androidx.appcompat.app.AlertDialog.Builder(newPlant.this)
.setTitle(null)
.setMessage("Where would you like to get your picture from?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Open Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dispatchTakePictureIntent();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton("Open Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
gallery.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(gallery,"Select Picture"), GALLERY_REQUEST_CODE);
}
})
.setIcon(android.R.drawable.ic_menu_camera)
.show();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
File f = new File(currentPhotoPath);
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(f).getPath());
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
uri = Uri.fromFile(f);
mediaScanIntent.setData(uri);
this.sendBroadcast(mediaScanIntent);
System.out.println(databaseHelper.getProfilesCount());
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
if (requestCode == GALLERY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
if (data != null){
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri curi = item.getUri();
uri = item.getUri();
File imageFile = new File(getRealPathFromURI(newPlant.this, curi));
//mArrayUri.add();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(curi);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
// DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
// Cursor cursor22 = mDatabaseHelper.GetPath();
// while (cursor22.moveToNext()){
// System.out.println("SELECTED " + cursor22.getString(i));
// }
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
Log.v("LOG_TAG", "Selected Images ");
}else {
//Toast.makeText(profuctadd.this,"NO IMAGE EXCEPTION",Toast.LENGTH_LONG).show();
System.out.println(data.getData());
if (data.getData()!=null){
Uri contentUri = data.getData();
uri = data.getData();
System.out.println("CONTENT URI "+contentUri);
File imageFile = new File(getRealPathFromURI(newPlant.this, uri));
System.out.println("FILE "+imageFile);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(uri);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
//DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
//Cursor cursor22 = mDatabaseHelper.GetPath();
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
// }
}
}
}
}
private String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
return "";
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private String getFileExt(Uri contentUri) {
ContentResolver c = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(c.getType(contentUri));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
Toast.makeText(newPlant.this,ex.getMessage(),Toast.LENGTH_LONG).show();
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.varroxsystems.plant.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}

How can I fix my app crash after take a photo in android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
How can I fix my app crash after take a photo in android, I am currently making an application to report to the streets via photos, but I have a problem when the user has taken a picture through the camera, when I press the application button to crash, the following reports of crashes that occur
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.dbothxrpsc119.soppeng/com.dbothxrpsc119.soppeng.LaporanActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4332)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4376)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at com.dbothxrpsc119.soppeng.LaporanActivity.setPic(LaporanActivity.java:262)
at com.dbothxrpsc119.soppeng.LaporanActivity.onCaptureImageResult(LaporanActivity.java:271)
at com.dbothxrpsc119.soppeng.LaporanActivity.onActivityResult(LaporanActivity.java:206)
at android.app.Activity.dispatchActivityResult(Activity.java:7351)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4328)
... 9 more
for the reportactivity code snippet as follows
public class LaporanActivity extends AppCompatActivity {
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private EditText edPesanKirim;
private Button btnUpload;
private ImageView ivImage;
private String userChoosenTask;
String mCurrentPhotoPath;
Uri photoURI;
public static final String UPLOAD_KEY = "image";
public static final String TAG = "Laporan";
private Bitmap bitmap;
private SQLiteDatabase db;
private Cursor c;
String pesan,nama,ktpsim,alamat,hp;
Boolean sudahUpload = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_laporan);
db=openOrCreateDatabase("User", Context.MODE_PRIVATE, null);
ivImage = (ImageView) findViewById(R.id.ivImage);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
edPesanKirim = (EditText) findViewById(R.id.edPesanKirim);
btnUpload = (Button) findViewById(R.id.btnUpload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//check jika data belum lengkap
c = db.rawQuery("SELECT * FROM users",null);
boolean exists = (c.getCount() > 0);
if(exists) {
c.moveToFirst();
pesan = edPesanKirim.getText().toString();
nama = c.getString(1);
ktpsim = c.getString(2);
alamat = c.getString(3);
hp = c.getString(4);
if (!c.getString(0).equals("") || !c.getString(1).equals("") || c.getString(2).equals("")
|| c.getString(3).equals("") || c.getString(4).equals("")) {
if (!pesan.equals("")) {
if (sudahUpload.equals(true)) {
uploadImage("gambar");
} else {
uploadImage("pesan");
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan isi gambar dan pesan terlebih dahulu",Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
startActivity(intent);
}
} else {
Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
startActivity(intent);
}
c.close();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Ambil Photo"))
cameraIntent();
else if(userChoosenTask.equals("Pilih dari Galery"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Ambil Photo", "Pilih dari Galery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(LaporanActivity.this);
builder.setTitle("Tambah Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(LaporanActivity.this);
if (items[item].equals("Ambil Photo")) {
userChoosenTask ="Ambil Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Pilih dari Galery")) {
userChoosenTask ="Pilih dari Galery";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Pilih File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
photoFile.delete();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("Photo",ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.dbothxrpsc119.soppeng.fileprovider",
photoFile);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "DebotHaxor_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
//mCurrentPhotoPath = "file:" + image.getAbsolutePath();
mCurrentPhotoPath = image.getAbsolutePath();
//mCurrentPhotoPath = image;
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = photoURI;
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void setPic() {
// Get the dimensions of the View
int targetW = ivImage.getWidth();
int targetH = ivImage.getHeight();
//Log.d("Photo","Set Pic "+mCurrentPhotoPath);
Bitmap real_bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap_view = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
ivImage.setImageBitmap(bitmap_view);
Log.d("Photo","Tampilkan Foto "+ mCurrentPhotoPath);
//resize
Bitmap resized;
resized = Bitmap.createScaledBitmap(bitmap_view,(int)(real_bitmap.getWidth()*0.4), (int)(real_bitmap.getHeight()*0.4), true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
bitmap = resized;
}
private void onCaptureImageResult() {
galleryAddPic();
setPic();
sudahUpload = true;
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
bitmap = bm;
sudahUpload = true;
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(String mode){
class UploadImage extends AsyncTask<Bitmap,Void,String> {
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LaporanActivity.this, "Kirim Pesan", "Mohon tunggu...",true,true);
loading.setCanceledOnTouchOutside(false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
String msg = "";
if (s.equals("ok")) {
msg = "Pesan sukses terkirim";
clearForm();
} else {
msg = getString(R.string.api_error);
}
Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Bitmap... params) {
HashMap<String,String> data = new HashMap<>();
if (params.length > 0) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
data.put(UPLOAD_KEY, uploadImage);
}
data.put("pesan", pesan);
data.put("device_id", Utility.uniqDevice(LaporanActivity.this));
String uri = "https://"+ getString(R.string.api_url) + "/path/kirim_pesan";
String result = rh.sendPostRequest(uri,data);
return result;
}
}
UploadImage ui = new UploadImage();
if (mode.equals("gambar"))
ui.execute(bitmap);
else
ui.execute();
}
private void clearForm() {
ivImage.setImageResource(R.drawable.ic_menu_gallery);
edPesanKirim.setText("");
btnSelect.setFocusable(true);
}
}
I believe that the problem is that you create uri for a file to store photo but didn't put it in intent. Please, try following:
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.dbothxrpsc119.soppeng.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(intent, REQUEST_CAMERA);
}

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)
{}}

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)

java.io.FileNotFoundException while posting image from Gallery to server

I want to post image selected through camera to server using multi part .I am getting exception here
java.io.FileNotFoundException: /external/images/media/26: open failed: ENOENT (No such file or directory)
Code is given below:
//On clicking Gallery
layout_gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadImageFromGallery();
}
});
public void loadImageFromGallery() {
popupWindow.dismiss();
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
String root = Environment.getExternalStorageDirectory().toString();
Log.e("root", root);
String directory_path = root + "/cam_intent/";
File myDir = new File(directory_path);
myDir.mkdirs();
File file = new File(myDir, "MyPhoto.jpg");
fileUri = Uri.fromFile(file);
Log.e("Uri of File", String.valueOf(fileUri));
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
launchUploadActivity(true);
} else if (requestCode == RESULT_LOAD_IMG) {
fileUri = data.getData();
//File file = new File(getRealPathFromURI(NewGroupActivity.this,uri));
//fileUri = Uri.fromFile(file);
Log.e("FileUriImageGallery", String.valueOf(fileUri));
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(fileUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.groupPic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
}
} else {
Toast.makeText(this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
Image is shown in the ImageView but is not sent to the server as it is thrown a FileNotFoundException.
private String uploadFile() {
Log.e("upload File", "called");
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
Log.e("URL", url_create_new_group);
HttpPost httppost = new HttpPost(url_create_new_group);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
if (val == 0) {
if (fileUri != null) {
Log.e("val = ", String.valueOf(val));
File sourceFile = new File(fileUri.getPath());
if (sourceFile != null) {
Log.e("SoureFile", String.valueOf(sourceFile));
photosize = 0;
entity.addPart("image", new FileBody(sourceFile));
} else {
photosize = 1;
Toast.makeText(NewGroupActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
}
}
} else {
File sourceFile = new File(picturePath);
if (sourceFile != null) {
photosize = 0;
entity.addPart("image", new FileBody(sourceFile));
} else {
photosize = 1;
Toast.makeText(NewGroupActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
}
}
totalSize = entity.getContentLength();
Log.e("Total Size", String.valueOf(totalSize));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
Please check the code.
Solved
Updated Working Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
launchUploadActivity(true);
} else if (requestCode == RESULT_LOAD_IMG) {
Uri uri = data.getData();
//File file = new File(getRealPathFromURI(NewGroupActivity.this,uri));
//fileUri = Uri.fromFile(file);
Log.e("FileUriImageGallery", String.valueOf(uri));
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.groupPic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
}

Categories