the app craches when changing the bitmap of image to uri - android

I've written a program(in android studio)that takes a picture when a button is clicked and that picture is sent automatically to Firebase storage. it was working fine, but when I take a picture it has a very low resolution. I was using the bitmap for that and I found that it is the reason so I changed it to uri. But I'm sure I did something wrong when changing the code to uri, because now when I take the picture it has a full resolution which is great but the app crashes before it sent the picture to the firebase storage.
here is my code :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static final int REQUEST_IMAGE_CAPTURE = 1;
private Button Sbutton;
private StorageReference mStorageRef;
Uri image;
String mCameraFileName;
private void dispatchTakePictureIntent() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent = new Intent();
//Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
DateFormat df = new SimpleDateFormat("-mm-ss");
String newPicFile = df.format(date) + ".jpg";
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mCameraFileName = outFile.toString();
Uri outuri = Uri.fromFile(outFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
startActivityForResult(intent, 2);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 2);
// startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorageRef = FirebaseStorage.getInstance().getReference();
Sbutton = findViewById(R.id.Tbutton);
Sbutton.setOnClickListener(this);
getSupportActionBar().hide();
}
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 2) {
ImageSwitcher imageView = null;
if (data != null) {
image = data.getData();
imageView.setImageURI(image);
imageView.setVisibility(View.VISIBLE);
uploadFile(image);
}
if (image == null && mCameraFileName != null) {
image = Uri.fromFile(new File(mCameraFileName));
imageView.setImageURI(image);
imageView.setVisibility(View.VISIBLE);
}
File file = new File(mCameraFileName);
if (!file.exists()) {
file.mkdir();
}
}
}
}
private <imageView> void uploadFile(imageView image) {
StorageReference mountainImagesRef = mStorageRef.child("images/" + String.valueOf(SystemClock.currentThreadTimeMillis()) + ".jpg");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
UploadTask uploadTask = mountainImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Log.d("downloadUrl-->", "" + task.getResult());
Toast.makeText(MainActivity.this, "Uploading Image Done", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}

I had a similar use-case like you have.
Please look at my solution that I've shared below:
String filePath;//Path of the file where image is stored
//Capture Image via camera
private void dispatchTakePictureIntent(int requestCode) {
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 = createImageFile(requestCode);
Uri photoURI = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
// Workaround for Android bug.
// grantUriPermission also needed for KITKAT,
// see https://code.google.com/p/android/issues/detail?id=76683
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
activity.grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
startActivityForResult(takePictureIntent, requestCode);
}
}
//create image file
private File createImageFile(int requestCode) {
// Create an image file name
String timeStamp = new SimpleDateFormat("-mm-ss", Locale.ENGLISH).format(new Date());
String imageFileName = timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(storageDir, imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
filePath = image.getAbsolutePath();
return image;
}
private void uploadImage() {
Uri file = Uri.fromFile(new File(filePath));
final StorageReference storageReference = storageRef.child("docs/" +
mobileNumber + "/" + file.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(file);
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Log.d(TAG, "onComplete: downloadUri: " + downloadUri.toString());
}
});
}

Related

Upload image to firebase failed when clicking anything in comfirmation page and the app crash

I have a question about upload image to firebase and it works before and after I done other activity...It failed...Can your guys help me...
The main error was when user click OK or CANCEL in confirmation page, the app crash. App will crash too when user select from gallery...
Here is the logcat...
2021-03-30 22:56:16.853 12576-12576/? E/in.firebasetes: Unknown bits set in runtime_flags: 0x8000
And here is the code for activity...
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users");
userID = user.getUid();
storageReference = FirebaseStorage.getInstance().getReference();
UserPic = (ImageView) findViewById(R.id.UserPic);
UserPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyPermission();
}
if (user != null){
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl()).into(UserPic);
}
}
}
private void VerifyPermission() {
if (ContextCompat.checkSelfPermission(UserProfile.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UserProfile.this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
}else {
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
selectOptionList();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
selectOptionList();
}else {
Toast.makeText(UserProfile.this, "Camera Permissions is required", Toast.LENGTH_LONG).show();
}
}
}
private void selectOptionList(){
selectList = getResources().getStringArray(R.array.selectList);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an option");
builder.setItems(selectList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
dispatchTakePictureIntent();
break;
case 1:
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, GALLERY_REQUEST_CODE);
break;
case 2:
dialog.dismiss();
break;
}
}
});
alertDialog = builder.create();
builder.show();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "interpayment.main.firebasetest.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + userID + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
Toast.makeText(UserProfile.this, "Opening Camera", Toast.LENGTH_SHORT).show();
return image;
}
private void uploadImageToFirebase(String name, Uri contentUri) {
final StorageReference img = storageReference.child("pictures/" + name);
img.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
img.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d("100", "onSuccess: Upload Image URL is " + uri);
Toast.makeText(UserProfile.this, "Uploaded", Toast.LENGTH_SHORT).show();
setUserProfileUrl(uri);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void setUserProfileUrl(Uri uri) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest request = new UserProfileChangeRequest.Builder().setPhotoUri(uri).build();
user.updateProfile(request).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(UserProfile.this, "Updated", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Failed set Profile", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == CAMERA_REQUEST_CODE) {
File f = new File(currentPhotoPath);
UserPic.setImageURI(Uri.fromFile(f));
Log.d("tag", "Absolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
uploadImageToFirebase(f.getName(), contentUri);
}else if(requestCode == GALLERY_REQUEST_CODE && data != null){
Uri img = data.getData();
Log.d("tag", "onActivityResult: Gallery Image Uri: " + img);
UserPic.setImageURI(img);
uploadImageToFirebase(currentPhotoPath, img);
}
}
}
I appreciate for your guys helping and thanks a lot for taking time to help me. Logcat was like this...
Logcat
----------------------------------------------------------------------
Update
My question is solved. The problem was the onStop function, I removed it. This is because the system set the [open camera] and [take photo from gallery] as new actitvity. So, if you have the onStop function, system close the apps when you open camera or others. This cause the apps automatically close and no any error in logcat.

Can not save picture from intent

I have a project witch have permission to camera and storage.
When the user click in some buttons the camera will be open by intent and take picture then saved it in the device to add it to firebase storage.
This operation was successful on most devices, but in Redmi A8(Android 10 , MIUI 12.0.1) it
was failed , the camera open then the application stop , maybe it failed to save the picture or failed to get it in ActicityResult.
Who I can solve it ?
Note: This is a part of methods in my code.
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(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.apps.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
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 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
currentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
public 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);
//showImage.setImageURI(Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
uploadImageToFirebase(f.getName(), contentUri);
}
}
}
private void uploadImageToFirebase(String name, Uri contentUri) {
final StorageReference image = storageReference.child("pictures/" + name);
image.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
image.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().child("Shifts").child(empId+"").
child(shiftKey).child(shiftImageType).setValue(uri+"");
alertDialog.dismiss();
}
});
startActivity(new Intent(getActivity() , MainActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage()+"", Toast.LENGTH_SHORT).show();
}
});
}

Android: How to store image from camera and show the in gallery?

I'm new in Android and I would create app that uses camera, store image taken from camera in device and show it in gallery? Anyone have any advice on how to do it? For now I have created the activity that allows you to take pictures but I don't know how to proceed to save and show the photos taken from the camera in the gallery. Please help me, I'm very desperate. Thanks in advance to everyone.
This is my code from android documentation:
public class CamActivity extends AppCompatActivity {
private ImageView imageView;
private Button photoButton;
private String currentPhotoPath;
private File photoFile = null;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_camera);
imageView = findViewById(R.id.taken_photo);
photoButton = findViewById(R.id.btnCaptureImage);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermissions()) {
dispatchTakePictureIntent();
galleryAddPic();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
} else {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
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 = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Camera");
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
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(CamActivity.this, "error" + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.myapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private boolean checkPermissions() {
//Check permission
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
//Permission Granted
return true;
} else {
//Permission not granted, ask for permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_IMAGE_CAPTURE);
return false;
}
}
}
allow camera and storage permission
public class CamActivity extends AppCompatActivity {
private ImageView imageView;
private Button photoButton;
private String currentPhotoPath;
private File photoFile = null;
private static final String TAG = "CamActivity";
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.taken_photo);
photoButton = findViewById(R.id.btnCaptureImage);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
captureImage();
}
});
}
#SuppressLint("QueryPermissionsNeeded")
private void captureImage() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(pictureIntent, 100);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
if (data != null && data.getExtras() != null) {
Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
saveImage(imageBitmap);
imageView.setImageBitmap(imageBitmap);
}
}
}
private void saveImage(Bitmap bitmap) {
String filename;
Date date = new Date(0);
#SuppressLint("SimpleDateFormat")
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename = sdf.format(date);
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream outputStream = null;
File file = new File(path, "/MyImages/"+filename + ".jpg");
File root = new File(Objects.requireNonNull(file.getParent()));
if (file.getParent() != null && !root.isDirectory()) {
root.mkdirs();
}
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
outputStream.flush();
outputStream.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (Exception e) {
Log.e(TAG, "saveImage: " + e);
e.printStackTrace();
}
}
}

Android: How to save image from camera to a specific folder and view it in my device's gallery?

as described in the title I would like to save the image from camera in a specific folder and then view it in the gallery of my device. So far I can access the camera, take the photo and show it in an ImageView in the same layout. How could I do? I read on the net to use the provider but using it, the images taken with the camera are not displayed in the gallery of my device. Thanks in advance to those who will answer.
This is my code:
public class CamActivity extends AppCompatActivity {
private ImageView imageView;
private Button photoButton;
private Button saveToGallery;
private String currentPhotoPath;
private File photoFile = null;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_camera);
imageView = findViewById(R.id.taken_photo);
photoButton = findViewById(R.id.btnCaptureImage);
saveToGallery = findViewById(R.id.gallery_save);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermissions()) {
dispatchTakePictureIntent();
galleryAddPic();
}
}
});
saveToGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
} else {
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
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 = Environment.getExternalStoragePublicDirectory(
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
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(CamActivity.this, "error" + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.myapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private boolean checkPermissions() {
//Check permission
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
//Permission Granted
return true;
} else {
//Permission not granted, ask for permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_IMAGE_CAPTURE);
return false;
}
}
}

Retrieving image from Mediastore is null

I'm trying to save an image from the camera of the phone and then retrieve it to save it on firebase storage.
I tryed a lot of ways of doing it, but I always get a null when I retrieve it.
Here it is how I make the picture with the camera:
private void camera() {
if (ActivityCompat.checkSelfPermission(MainChatActivity.this,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, PHOTO_CAMERA_IMAGE);
}
}
Here I save it on the phone:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (data != null)
uploadImage(data.getData());
break;
case PHOTO_CAMERA_IMAGE:
if (resultCode == RESULT_OK) {
if (data != null) {
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();
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"borealos.com.chat.fileprovider",
photoFile);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, photoURI));
takePictureIntent.putExtra("foto", photoURI);
Uri uri = (Uri) takePictureIntent.getExtras().get(MediaStore.EXTRA_OUTPUT);
uploadImage(photoURI);
// startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
} catch (IOException ex) {
// Error occurred while creating the Fil
}
}
}
}
break;
}}
And here I retrieve it for uploading on firebase:
private void uploadImage( final Uri filePath) {
Uri filePath2=filePath;
final String s;
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
s = UUID.randomUUID().toString();
ref = storageReference.child("images/" + s);
ref.putFile(filePath)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
sendImage(filePath, task.getResult().getDownloadUrl().toString());
}
}
});
}
}
Thanks for the help in advice

Categories

Resources