When I try to save an image to an external directory, the directory is successfully scanned by MediaScannerConnection, but the images are not shown in gallery.
public void saveItem() {
if (selectCount == 0) {
Toast.makeText(getActivity(), "Select at least one image", Toast.LENGTH_SHORT).show();
} else {
Iterator iterator = selectedFile.iterator();
while (iterator.hasNext()) {
gridFilePath = new File(iterator.next().toString());
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myImages/";
File destination = new File(destinationPath);
try {
FileUtils.copyFileToDirectory(gridFilePath, destination);
MediaScannerConnection.scanFile(getActivity(), new String[]{destinationPath},
null, new MediaScannerConnection.MediaScannerConnectionClient() {
#Override
public void onMediaScannerConnected() {
}
#Override
public void onScanCompleted(String path, Uri uri) {
Log.d("Scan","Scanning Completed");
}
}
);
Log.d("Image Saved", "Saved");
} catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(getActivity(), "Pictures Saved", Toast.LENGTH_LONG).show();
}
}
I fixed my problem adding the file's mimeType:
private void notifyNewFileToSystem(File file) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath());
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
MediaScannerConnection.scanFile(getApplicationContext(),
new String[]{file.getAbsolutePath()},
new String[]{type},
(path, uri) -> {
Log.e(TAG, "Path: " + path);
Log.e(TAG, "Uri: " + uri);
}
);
}
I found the solution to get the mimeType here:
https://stackoverflow.com/a/8591230/2077248
Related
I want the application in the background to be able to take a screenshot and save the result to the clipboard. Is there an optimal solution to this problem?
You can use the following code examples
public class HelperScreenShot {
public static Bitmap takeScreenshot(View v) {
v.setDrawingCacheEnabled(true);
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
return b;
}
public static Bitmap takeScreenshotOfRootView(View v) {
return takeScreenshot(v.getRootView());
}
public static boolean takeScreenshotAndSaveIi(View v, String filename) {
return storeScreenshot(takeScreenshot(v.getRootView()), filename);
}
public static boolean storeScreenshot(Bitmap bitmap, String filename) {
if (!isExternalStorageReadable()) {
return false;
}
if (!isExternalStorageWritable()) {
return false;
}
OutputStream out;
try {
File dir = getDownloadStorageDir("ScreenShots");
File imageFile = new File(dir, filename + ".jpg");
if (!imageFile.exists()) {
imageFile.createNewFile();
}
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
MediaScannerConnection.scanFile(G.context, new String[]{imageFile.getAbsolutePath()}, null, null);
out.flush();
out.close();
return true;
} catch (FileNotFoundException e) {
// manage exception ...
return false;
} catch (IOException e) {
// manage exception ...
return false;
}
}
/* Checks if external storage is available for read and write */
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
/* Checks if external storage is available to at least read */
private static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
private static File getDownloadStorageDir(String fileName) {
// Get the directory for the user's public pictures directory.
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
if (!Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).exists()) {
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()).mkdirs();
}
if (!storageDir.exists()) {
storageDir.mkdir();
}
return storageDir;
}
}
private Single<Boolean> loadImage() {
Date date = new Date();
filename = "receipt" + date.getTime();
return Single.just(HelperScreenShot.takeScreenshotAndSaveIi(binding.v, filename));
}
private void getScreenshot() {
loadImage()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Boolean>() {
#Override
public void onSubscribe(#io.reactivex.annotations.NonNull Disposable d) {
disposables.add(d);
}
#Override
public void onSuccess(#io.reactivex.annotations.NonNull Boolean s) {
if (s) {
Snackbar snackbar = Snackbar.make(binding.v, getResources().getString(R.string.picture_save_to_galary), Snackbar.LENGTH_LONG);
snackbar.setAction(getResources().getString(R.string.navigation_drawer_open), new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ScreenShots/" + filename + ".jpg");
Log.d("amini", "onClick: " + file.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file) :
Uri.fromFile(file), "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
});
snackbar.show();
} else {
Snackbar snackbar = Snackbar.make(binding.v, getResources().getString(R.string.str_frag_sync_error), Snackbar.LENGTH_LONG);
snackbar.setAction(getResources().getString(R.string.ok), v -> snackbar.dismiss());
snackbar.show();
}
}
#Override
public void onError(#io.reactivex.annotations.NonNull Throwable e) {
}
});
}
I am trying to record video using mediarecorder and display that video on other activity. It was working fine and the video was there but now a error is occuring that video cannot be displayed. Can someone help?
Here my code :
captureButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
isActionDown = true;
try {
if (isActionDown) {
initRecorder();
if (isActionDown)
prepareRecorder();
isPrepared = true;
}
if (isPrepared && isActionDown) {
Toast.makeText(getContext(), "startRecorder", Toast.LENGTH_LONG).show();
isRecording = true;
mediaRecorder.start();
} else {
releaseMediaRecorder();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("onLongPress Error ", e.toString());
}
return true;
}
});
captureButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
isActionDown = false;
try {
if (isRecording) {
if (mediaRecorder != null) {
mediaRecorder.stop();
releaseMediaRecorder(); // release the MediaRecorder object
camera.lock();
Toast.makeText(getContext(), "MediaRecoderNull", Toast.LENGTH_LONG).show();
}
isRecording = false;
if (fileUri != null) {
playVideo(getView());
}
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
return false;
}
});
Uri fileUri = null;
Uri ImageUri;
private void initRecorder() {
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setOrientationHint(90);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
}
private void prepareRecorder() {
mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
try {
mediaRecorder.prepare();
isPrepared = true;
return;
} catch (IllegalStateException e) {
releaseMediaRecorder();
e.printStackTrace();
} catch (IOException e) {
releaseMediaRecorder();
e.printStackTrace();
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void playVideo(View view) {
Intent playIntent = new Intent(getActivity(), CapturedVideoActivity.class);
playIntent.putExtra("videoUri", fileUri.toString());
startActivity(playIntent);
}
so on the next screen while displaying this occurs enter image description here
Next screen code:
VideoView mVideoView = findViewById(R.id.videoCaptured);
videoUri = Uri.parse(getIntent().getExtras().getString("videoUri"));
mVideoView.setVideoURI(videoUri);
mVideoView.start();
I want to add feature in my app to download a GIF Image from url to my phones storage.
How can I do this into my application
public class Download {
Context context;
String url;
ProgressDialog progressDailog;
public void saveImage(Context context, String url) {
this.context = context;
this.url = url;
progressDailog = new ProgressDialog(context);
progressDailog.setMax(100);
progressDailog.setMessage("Please wait...");
progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDailog.setCanceledOnTouchOutside(false);
progressDailog.show();
Glide.with(context).asBitmap()
.load(url)
.apply(new RequestOptions()
.diskCacheStrategyOf(DiskCacheStrategy.ALL)
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
progressDailog.dismiss();
storeImage(resource);
//Log.d(TAG, "Image : " + resource);
}
});
}
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
Toast.makeText(context, "Image Downloaded", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs())
return null;
}
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS.jpg");
return mediaFile;
}
}
From this code I can download the normal Image but it did not works on GIF. The GIF image downloaded and it remains static
This snippet will help you to download gif using GLIDE
Glide.with(context)
.download(url)
.listener(new RequestListener<File>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
progressDailog.dismiss();
Toast.makeText(context, "Error saving", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
progressDailog.dismiss();
try {
saveGifImage(context, getBytesFromFile(resource), createName(url));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}).submit();
createName function
public String createName(String url) {
String name = url.substring( url.lastIndexOf('/')+1, url.length());
String NoExt = name.substring(0, name.lastIndexOf('.'));
if(!ext.equals(".gif")){
name = NoExt + ".jpg";
}
return name;
}
getBytesFromFile function
public byte[] getBytesFromFile(File file) throws IOException {
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("File is too large!");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
return bytes;
}
saveGifImage function
public void saveGifImage(Context context, byte[] bytes, String imgName ) {
FileOutputStream fos = null;
try {
File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File customDownloadDirectory = new File(externalStoragePublicDirectory, "Merry_Christmas");
if (!customDownloadDirectory.exists()) {
boolean isFileMade = customDownloadDirectory.mkdirs();
}
if (customDownloadDirectory.exists()) {
File file = new File(customDownloadDirectory, imgName);
fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
if (file != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, file.getName());
values.put(MediaStore.Images.Media.DISPLAY_NAME, file.getName());
values.put(MediaStore.Images.Media.DESCRIPTION, "");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/gif");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
ContentResolver contentResolver = context.getContentResolver();
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(context, "Image saved to " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
For getting GIF using Glide:
Glide.with(MainActivity.this).asFile()
.load(url)
.apply(new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new Target<File>() {
#Override
public void onStart() {
}
#Override
public void onStop() {
}
#Override
public void onDestroy() {
}
#Override
public void onLoadStarted(#Nullable Drawable placeholder) {
}
#Override
public void onLoadFailed(#Nullable Drawable errorDrawable) {
}
#Override
public void onResourceReady(#NonNull File resource, #Nullable Transition<? super File> transition) {
storeImage(resource);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
#Override
public void getSize(#NonNull SizeReadyCallback cb) {
}
#Override
public void removeCallback(#NonNull SizeReadyCallback cb) {
}
#Override
public void setRequest(#Nullable Request request) {
}
#Nullable
#Override
public Request getRequest() {
return null;
}
});
For Saving Image:
private void storeImage(File image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream output = new FileOutputStream(pictureFile);
FileInputStream input = new FileInputStream(image);
FileChannel inputChannel = input.getChannel();
FileChannel outputChannel = output.getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
output.close();
input.close();
Toast.makeText(MainActivity.this, "Image Downloaded", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs())
return null;
}
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS_"+Calendar.getInstance().getTimeInMillis() +".gif");
return mediaFile;
}
Glide can get File, worked with me:
Glide.with(context).asFile()
.load(url)
.apply(new RequestOptions()
.diskCacheStrategyOf(DiskCacheStrategy.ALL)
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new SimpleTarget<File>() {
#Override
public void onResourceReady(#NonNull File resource, #Nullable Transition<? super File> transition) {
progressDailog.dismiss();
storeImage(resource);
//Log.d(TAG, "Image : " + resource);
}
});
I am uploading image file to S3 via the AWS java SDK, but i am getting the below error while uploading , i have checked my credentials and my bucket they are fine
Unable to calculate MD5 hash: /data/user/0/competent.groove.feetport/files/data/user/0/competent.groove.feetport/app_imageDir/IMG_20161122_073058.jpg: open failed: ENOENT (No such file or directory)
I am capturing the image from camera and saving the image in phone , here is my code
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
//Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT) .show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
// This demo app saves the taken picture to a constant file.
// $ adb pull /sdcard/Android/data/com.google.android.cameraview.demo/files/Pictures/picture.jpg
///storage/7A52-13E8/Android/data/competent.groove.feetport/files/Pictures/picture.jpg
//make a new picture file
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Toast toast = Toast.makeText(getActivity(), "Picture Not saved", Toast.LENGTH_LONG);
toast.show();
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast toast = Toast.makeText(getActivity(), "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
toast.show();
Log.e("-pictureFile--length-----",""+pictureFile.length());
Log.e("---pictureFile-----"+pictureFile.getName(),""+pictureFile.getAbsolutePath());
Log.e("-fileName--",""+fileName);
editor = sharedPref.edit();
editor.putString(Constants.PIC_PATH,""+fileName);
editor.commit();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
});
}
};
String fileName="";
//make picture and save to a folder
private File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
/* File mediaStorageDir = new File("/sdcard/", "JCG Camera");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}*/
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
ContextWrapper cw = new ContextWrapper(getActivity());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
Log.e("---directory-----", "" + directory);
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
///data/user/0/competent.groove.biometric/files/IMG_20160803_181740.jpg
//and make a media file:
fileName = directory + File.separator + "IMG_" + timeStamp + ".jpg";
mediaFile = new File(directory + File.separator + "IMG_" + timeStamp + ".jpg");
Log.e("---extStorageDirectory-----", "" + extStorageDirectory);
//Log.e("---mediaFile-----",""+mediaFile.length());
//Log.e("---mediaFile-----"+mediaFile.getName(),""+mediaFile.getAbsolutePath());
return mediaFile;
}
and my aws code to upload file is
public class UploadAws extends AsyncTask{
private int total, percentage = 0;
Context context;
String s3_server_path = "";
ObscuredSharedPreferences shrdpref;
ObscuredSharedPreferences.Editor editor;
String res = "";
public UploadAws(Context context){
Log.e(""+getClass(), "UploadAws constructor called");
this.context = context;
shrdpref = new ObscuredSharedPreferences(context, context.getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE));
}
#Override
protected Object doInBackground(Object... params) {
try {
Log.d("" + getClass(), "UploadAws doInBackground called");
File pictures = null;
AmazonS3Client s3Client = null;
TransferUtility tx = null;
percentage = 0;
try {
s3_server_path = shrdpref.getString(Constants.PIC_PATH,"");
File dir = context.getFilesDir();
pictures = new File(dir, s3_server_path);
s3Client = new AmazonS3Client(new BasicAWSCredentials(shrdpref.getString(Constants.AWS_Access_Key,""),shrdpref.getString(Constants.AWS_Secret_Key,"")));
tx = new TransferUtility(s3Client,context);
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
Log.e("------File length--------=", "" + pictures.length());
Log.e("------File getName--------=", "" + pictures.getName());
Log.e("------File getAbsolutePath--------=", "" + pictures.getAbsolutePath());
s3Client.setEndpoint("s3.amazonaws.com");
String Feetport_bucket = shrdpref.getString(Constants.fs_bucket, "");
if (s3Client.doesBucketExist(Feetport_bucket)) {
Log.e("Warn", "service called bucket exist");
} else {
s3Client.createBucket(Feetport_bucket);
Log.e("FOS signature", "Bucket created");
}
int imageIndex = pictures.toString().lastIndexOf("/");
String pictureString = pictures.toString().substring(imageIndex + 1, pictures.toString().length());
String selfie_url = "FeetPort/" + shrdpref.getString(Constants.company_name, "") + "/attend/" + Utils.getCurrentDate() + "/" + pictureString;
Log.d("UploadAws selfie_url called: ", "" + selfie_url);
//https://feetport.s3.amazonaws.com/8632/17/20161122/mayank1_I_1624_065610_COL22.jpeg
final TransferObserver observer = tx.upload(Feetport_bucket, pictures.getName(), pictures);
observer.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int arg0, TransferState state) {
Log.e("onStateChanged", "on state changed " + state);
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
Log.e("onProgressChanged", "total bytes " + observer.getBytesTotal());
Log.e("onProgressChanged", "total bytes transfered " + observer.getBytesTransferred());
percentage = (int) (bytesCurrent / bytesTotal * 100);
Log.e("onProgressChanged", "total percentage " + percentage);
}
#Override
public void onError(int arg0, Exception arg1) {
Log.e("onError=" + arg0, "on Error " + arg1.toString());
percentage = 101;
}
});
do {
} while (percentage < 100);
Log.e("percentage", "percentage " + percentage);
if (percentage == 100) {
/**
* CGPL-17 9-5-2016 dynamic bucket and url.
*/
String S3_SERVER = "https://".concat(Feetport_bucket).concat(".s3.amazonaws.com/");
String imageUrl = S3_SERVER + selfie_url;
//Session.setselfie_url(shrdpref, imageUrl);
editor = shrdpref.edit();
editor.putString(Constants.PIC_PATH, "" + imageUrl);
editor.commit();
Log.e("Selfie url ", "imageUrl --- " + imageUrl);
/*JsonParameters object = new JsonParameters(context);
object.markedAttendance(callback);*/
} else {
/*JsonParameters object = new JsonParameters(context);
object.markedAttendance(callback);*/
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
}
This isn't anything related to S3.
ENOENT (No such file or directory) is a local error: file not found.
Take a very close look at the path in the error message. I've included the path here, and added some line breaks for readability. I did not otherwise edit this, and, importantly, I did not paste any of it here more than once:
/data/user/0
/competent.groove.feetport
/files/data/user/0
/competent.groove.feetport
/app_imageDir/IMG_20161122_073058.jpg
I'm not saying that this is wrong, but it certainly looks wrong. It certainly looks like you're trying to upload the file from a path that you have incorrectly constructed, with some duplication in the directory structure... and there's no such directory, no such file.
I am using following code to upload a file to Dropbox. But I want to check if the file exists on Dropbox already, to avoid duplications. So how can I check if a file already exists or not? As I am new to Android, I don't know what to do now
public class UploadFileToDropbox extends AsyncTask<Void, Void, Boolean>
{
private DropboxAPI<?> dropbox;
private String path;
private Context context;
public UploadFileToDropbox(Context context, DropboxAPI<?> dropbox,
String path) {
this.context = context.getApplicationContext();
this.dropbox = dropbox;
this.path = path;
}
#Override
protected Boolean doInBackground(Void... params) {
final File tempDir = context.getCacheDir();
File tempFile;
FileWriter fr;
try {
tempFile = File.createTempFile("file", ".txt", tempDir);
fr = new FileWriter(tempFile);
fr.write("Test file uploaded using Dropbox API for Android");
fr.close();
FileInputStream fileInputStream = new FileInputStream(tempFile);
dropbox.putFile(path + "sample.txt", fileInputStream,
tempFile.length(), null, null);
tempFile.delete();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(context, "File Uploaded Successfully!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed to upload file", Toast.LENGTH_LONG)
.show();
}
}
}
If the file exists, then the Entry is not null
public boolean isExists(String path) {
boolean ret = false;
try {
Entry existingEntry = metadata(path, 1, null, false, null);
if (existingEntry != null) {
ret = true;
}
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = false;
}
return ret;
}
private void loadFiles(final String directory) {
new Thread() {
#Override
public void run() {
String mPath = directory;
Entry direntEx = null;
try {
direntEx = mApi.metadata(mPath, 1000, null, true, null);
} catch (DropboxException e) {
e.printStackTrace();
}
if (direntEx.contents.size() != 0) {
for (Entry ent : direntEx.contents) {
String name = ent.fileName();
/*Compare file here*/
}
}
super.run();
}
}.start();
}