How to upload images gotten from camera using Android Upload Service - java

I have been able to make users upload photos to server taken from their gallery, but when a user uses camera to capture live and upload, I get this error unsupported scheme: file::///storage/...
I am using android upload service library
implementation "net.gotev:uploadservice:3.5.2"
I searched and discovered that file:// scheme is not allowed to be attached with Intent.
1. Selecting image from camera on button click
capture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
FileProvider.getUriForFile(UploadActivity2.this, BuildConfig.APPLICATION_ID + ".provider",
createImageFile()));
startActivityForResult(intent, 0);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
2. Getting the image captured
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 0:
try {
Uri cameraPath = FileProvider.getUriForFile(UploadActivity2.this,
BuildConfig.APPLICATION_ID + ".provider", createImageFile());
String stringUri = cameraPath.toString();
selectedImages.add(stringUri);
}catch (IOException ex) {
ex.printStackTrace();
Glide.with(this)
.load(cameraFilePath)
.into(display_image);
break;
}
}
As you see, I am using file provider to get Uri and storing the uri in a variable called selectedimages so I can pass it through an intent to another activity where the upload occurs
createImageFile method
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.UK).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
//This is the directory in which the file will be created. This is the default location of Camera photos
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 using again
cameraFilePath = "file://" + image.getAbsolutePath();
return image;
}
3. Passing intent PATH, to uploadActivity
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putStringArrayListExtra("PATH", selectedImages);
startActivity(intent);
}
});
5. UploadAcvity where the upload happens
public void upload() {
ArrayList<String> selectedImages = getIntent().getStringArrayListExtra("PATH");
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, EndPoints.UPLOAD_URL)
.addFileToUpload(selectedImages.get(0), "image") //Adding file
.addParameter("caption", captionx) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(0)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Using this.
a. The image is not displaying in point 2 using Glide.with(this)
.load(cameraFilePath)
.into(display_image);
b. The image uploads but it is an empty file of 0 bytes.
But when I change the value of the variable of selectedImages in point 2 from selectedImages.add(stringUri); to selectedImages.add(cameraFilePath);
b. After clicking upload, I get error unsupported scheme: file::///storage/

Found the answer.
1. In the createImageFile method. I had to get the coontent:// url from the captured file using -
File newFile = new File(storageDir, image.getName());
contentUrl = FileProvider.getUriForFile(UploadActivity2.this,
BuildConfig.APPLICATION_ID + ".provider", newFile);
stringContentUrl = contentUrl.toString();
2. Then I passed the stringContentUrl into selected images String while getting the image captured.
selectedImages.add(stringContentUrl);
3. Passed it through an intent Extra and called it in the uploadActivity as seen in point 3 and 4 in the question.

Related

Download pdf in android 11

I have upgraded to android 11. I am having an issue downloading PDF files.
I have used this code:
private void createFile(Uri pickerInitialUri, String title) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, title);
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when your app creates the document.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
}
startActivityForResult(intent, CREATE_FILE);
}
The file is created but the file is empty. I am still unable to save the downloaded pdf file.
I used to use DownloadManager request to download the pdf file from web.
DownloadManager downloadManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
if (SDK_INT > Build.VERSION_CODES.Q) {
// Uri uri1 = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "")); //before android 11 this was working fine
// Uri uri1 = Uri.fromFile(new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), ""));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true).setTitle(title + strDate + ".pdf")
.setDescription(description)
//.setDestinationUri(uri1) // before android 11 it was working fine.
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title + strDate + ".pdf") // file is not saved on this directory.
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);//to show the DOWNLOAD notification when completed
// createFile(uri , title + strDate + ".pdf"); // for new scoped storage
} else {
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true).setTitle(title + strDate + ".pdf")
.setDescription(description)
.setDestinationInExternalPublicDir(FileUtils.downloadPdfDestination(), title + strDate + ".pdf")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //to show the DOWNLOAD notification when completed
}
long PDF_DOWNLOAD_ID = downloadManager.enqueue(request);```
ACTION_CREATE_DOCUMENT is used to create a new document. If one already existed, it will be overwritten. If you want to view an existing document, use ACTION_VIEW.
Of course none of the code you posted actually downloads a PDF. If you need help with that, post your DownloadManager code.
Check this code snippet:
override fun startDownload(url: String, onError: (e: Exception) -> Unit) {
try {
val request = DownloadManager.Request(Uri.parse(url))
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
UUID.randomUUID().toString()
)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION)
(context.getSystemService(DOWNLOAD_SERVICE) as DownloadManager).enqueue(request)
} catch (e: Exception) {
e.printStackTrace()
onError.invoke(e)
}
}
It's working fine on Android 11 by using DownloadManger API.
Use below code to download & view pdf.
First you need to apply rxjava dependency for background task.
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Don't forgot to check WRITE_EXTERNAL_STORAGE permission before call below method. Also check INTERNET permission as well.
Then use below method to perform operation in background.
private void downloadAndOpenInvoice() {
mDialog.show();
Observable.fromCallable(() -> {
String pdfName = "Invoice_"+ Calendar.getInstance().getTimeInMillis() + ".pdf";
String pdfUrl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
File file = CommonUtils.downloadFile(mActivity, pdfUrl, pdfName,mDialog);
return file;
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(file -> {
CommonUtils.viewPdf(file, mActivity, mDialog);
});
}
To download file from url use below snippet
public static File downloadFile(Activity mActivity, String url, String fileName, CustomDialog mDialog) {
// write the document content
File fileDir = new File(CommonUtils.getAppDir(mActivity, "Invoice")); //Invoice folder inside your app directory
if (!fileDir.exists()) {
boolean mkdirs = fileDir.mkdirs();
}
File pdfFile = new File(CommonUtils.getAppDir(mActivity, "Invoice"), fileName); //Invoice folder inside your app directory
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(pdfFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
Toast.makeText(mActivity, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
return pdfFile;
}
for app directory
public static String getAppDir(Context context, String folderName) {
return context.getExternalFilesDir(null).getAbsolutePath() + File.separator + folderName + File.separator;
}
Use below code to view pdf
public static void viewPdf(File pdfFile, Activity mActivity, CustomDialog mDialog) {
Uri uri = FileProvider.getUriForFile(mActivity, mActivity.getApplicationContext().getPackageName() + ".provider", pdfFile);
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setDataAndType(uri, "application/pdf");
//pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
});
mActivity.startActivity(pdfIntent);
Log.e("Invoice - PDF", pdfFile.getPath());
} catch (ActivityNotFoundException e) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
});
e.printStackTrace();
Log.e("Invoice - PDF", "Can't read pdf file");
Toast.makeText(mActivity, "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
}

How to attach image to email on Android emailIntent

To send the email the method for the button is;
public void buttonSendEmailClicked(View view) {
File file = saveFileToShare();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Check Out MyPic");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Taken With Android!");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), interstitial_request);
}
The saveFileToShare element is this;
public File saveFileToShare() {
try
{
File fileImage = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/attachment.png");
if(!fileImage.exists())
{
fileImage.delete();
}
editorImage.setDrawingCacheEnabled(true);
Bitmap bitmap = editorImage.getDrawingCache();
fileImage.createNewFile();
FileOutputStream ostream = new FileOutputStream(fileImage);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
editorImage.invalidate();
editorImage.setDrawingCacheEnabled(false);
return fileImage;
}
catch (Exception e)
{
System.out.print(e);
e.printStackTrace();
return null;
}
}
Saving the image works fine, the save code is;
public void buttonSaveImageClicked(View view) throws IOException {
editorImage.setDrawingCacheEnabled(true);
Bitmap bitmap = editorImage.getDrawingCache();
SaveLayoutToFile saveImage = new SaveLayoutToFile(this, bitmap, editorImage);
String filePath = Environment.getExternalStorageDirectory() + "/DCIM/Camera/wonkydog";
saveImage.execute(filePath);
}
I need to set the email code to grab the image and attach to email.
At the moment when I press the email button it just returns to the title screen without doing anything else.
If I comment out this line
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
Then it opens the mail send dialogue, but without attachment of course...
I found the answer, rather than using the emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
I replaced it with;
emailIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(EditorActivity.this, "com.myapp.myappname.provider", file));
It now works correctly!

How to save Captured Images to Custom path in android Storage

I have built an Camera application following a Tutorial from Youtube. It saves the Files on External Storage with following code
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
}
}
}
But, I would like to show a Dialog box to user when app starts with directory chooser dialog where they want to save images which I followed the Tutorial from this link https://www.codeproject.com/Articles/547636/Android-Ready-to-use-simple-directory-chooser-dial
The code for Directory choose dialog is below
DirectoryChooserDialog directoryChooserDialog =
new DirectoryChooserDialog(MainActivity.this,
new DirectoryChooserDialog.ChosenDirectoryListener()
{
#Override
public void onChosenDir(String chosenDir)
{
m_chosenDir = chosenDir;
Toast.makeText(
MainActivity.this, "Chosen directory: " +
chosenDir, Toast.LENGTH_LONG).show();
}
});
// Toggle new folder button enabling
directoryChooserDialog.setNewFolderEnabled(m_newFolderEnabled);
// Load directory chooser dialog for initial 'm_chosenDir' directory.
// The registered callback will be called upon final directory selection.
directoryChooserDialog.chooseDirectory(m_chosenDir);
m_newFolderEnabled = ! m_newFolderEnabled;
And also indeed, I have a separate class of DirectoryChooserDialog.
Now how do I merge the first code with second one such that when Image taken from camera will save to the folder that users selected from second code not to external storage Directory as specified by first code.
Image file for DirectoryChooserDialog appears as

Image wont attach to a text message even with a working URI

When I push the Share button, the SMS body goes in just fine, but I just can't get the image to show up. It just doesn't even look like there is any attachment.
I looked over all of my code and it looks fine, but I can't say I'm an expert on development yet so I'm probably looking over something.
Does anyone know what could be going on?
Getting the URI from the database (I know the URI is correct because an imageview displays correctly based on this same URI):
imageURI = Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE)));
This is where I try to set the URI to the attachment:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_shareWine) {
Intent intentShare = new Intent(Intent.ACTION_SENDTO);
intentShare.setData(Uri.parse("smsto:")); // This ensures only SMS apps respond
intentShare.putExtra("sms_body", "The sms body goes here";
//Attaching the image I want into the text:
intentShare.putExtra(intentShare.EXTRA_STREAM, imageURI);
if (intentShare.resolveActivity(getPackageManager()) != null) {
startActivity(intentShare);
}
And it case it helps, this is how I'm getting the URI originally:
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) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"jeremy.com.wineofmine.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
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 image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
I fixed it by changing the intentShare code to this:
Intent intentShare = new Intent(Intent.ACTION_SEND);
intentShare.putExtra(intentShare.EXTRA_STREAM, imageURI);
intentShare.setType("image/*");
intentShare.putExtra(Intent.EXTRA_TEXT, "The sms body goes here");
if (intentShare.resolveActivity(getPackageManager()) != null) {
startActivity(intentShare);
}
ModularSynth helped me realize that ACTION_SENDTO wouldn't work, since that is only text.
Another thing that might help someone is that when I changed to ti ACTION_SEND, it was only putting in the image at first, with no body. I fixed that also.
Instead of this line:
intentShare.putExtra("sms_body", "The sms body goes here";
Replace it with:
intentShare.putExtra(Intent.EXTRA_TEXT, "The sms body goes here");
That will let you send both the image and the text in the MMS.
Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) to the ACTION_SEND Intent before calling startActivity(). Right now, you are attaching the Uri, but the recipient has no rights to read the content identified by that Uri.

Proper way how to get image from gallery and captured photos?

My attempt does not work at all unfortunately. Weirdly enough, capturing photos from camera works when debugging but does not in production.
#Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (!Debug.isDebuggerConnected()){
Debug.waitForDebugger();
Log.d("debug", "started"); // Insert a breakpoint at this line!!
}
if (resultCode != RESULT_OK) {
return;
}
File file = null;
Uri path = null;
Bitmap image = null;
switch (requestCode) {
case RequestCodes.REQUEST_IMAGE_CAPTURE:
Bundle extras = data.getExtras();
image = (Bitmap) extras.get("data");
file = ImageUtils.saveToFile(image, "profile_picture", this);
mProfileImageView.setImageBitmap(image);
mCurrentAbsolutePath = file.getAbsolutePath();
break;
case RequestCodes.REQUEST_IMAGE_SELECT:
path = data.getData();
mProfileImageView.setImageURI(path);
mCurrentAbsolutePath = path.getPath();
file = new File(mCurrentAbsolutePath);
image = BitmapFactory.decodeFile(mCurrentAbsolutePath, new BitmapFactory.Options());
break;
default:
break;
}
try {
if(RequestCodes.REQUEST_IMAGE_SELECT == requestCode){
file = File.createTempFile(
"user_picture", /* prefix */
".jpeg", /* suffix */
getExternalFilesDir(Environment.DIRECTORY_PICTURES) /* directory */
);
File pathFile = new File(ImageUtils.getPath(path, this));
GeneralUtils.copy(pathFile, file);
}
} catch (IOException e) {
e.printStackTrace();
}
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, 100, 100);
String thumbnailPath = null;
// Edited source: https://stackoverflow.com/a/673014/6519101
FileOutputStream out = null;
try {
// PNG is a lossless format, the compression factor (100) is ignored
thumbnailPath = File.createTempFile(
"user_picture_thumbnail", /* prefix */
".png", /* suffix */
getExternalFilesDir(Environment.DIRECTORY_PICTURES) /* directory */
).getAbsolutePath();
out = new FileOutputStream(thumbnailPath);
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
String finalPath = file.getPath();
UserClient client = new UserClient();
String finalThumbnailPath = thumbnailPath;
client.changeUserPicture(file, FileUtils.getMimeType(this, Uri.fromFile(file)), new ApiListener<Response<ResponseBody>>(this){
#Override
public void onSuccess(Response<ResponseBody> response, int statusCode) {
SharedPreferencesManager preferences = SharedPreferencesManager.getInstance();
preferences.put(SharedPreferencesManager.Key.ACCOUNT_IMAGE_PATH, finalPath);
preferences.put(SharedPreferencesManager.Key.ACCOUNT_IMAGE_THUMBNAIL_PATH, finalThumbnailPath);
super.onSuccess(response, statusCode);
}
});
}
Unfortunately when debugging the from example of a path "/0/4/content://media/external/images/media/54257/ORIGINAL/NONE/1043890606" decoded file end up being null and breaks everything.
What is the best way of both getting from gallery and capturing image from photo?
What you should be using are content providers and resolvers here which can be thought of as databases and accessing databases for easier understanding.
That path you have there is called a URI, which is essentially like a link to a database entry. Both the camera and gallery uses content providers and resolvers actively. When a photo is taken, it is saved but the camera app also lets content provider know a new entry has been added. Now every app who has the content resolvers, such as the gallery app, can find that photo because the URI exist.
So you should be following the guides to implement content resolver if you want to access all photos in gallery.
As an aside, if you use code to copy an image file but does up update the content providers, your other app cannot see that new copied file unless it knows the absolute path. But when you restart your phone, some system does a full recheck for all image files and your content provider could be updated with the newly copied file. So try restarting your phone when testing.

Categories

Resources