AWS Unable to calculate MD5 hash Android - java

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.

Related

Trying to save images to directory, Saving into an unknown place

I am trying to create a facial/emotion detection application for my dissertation and have hit the wall that has stopped me from progressing and I cant figure out the reason why it is preventing the image saving to the directory of the phone. It seems to be saving to the SD card, but I dont use an SDcard in my phone / an emulated DCIM.
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+ "/" + UUID.randomUUID(), toString()+ ".jpg");
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes() [0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (IOException e)
{
e.printStackTrace();
}
finally {
{
if (image != null)
image.close();
}
}
}
This is the code I have to create the file and save to the location, I have tried other solutions but they throw out errors.
File folder = new File(Environment.getExternalStorageDirectory() + "/CustomFolder");
File file;
if (!folder.exists()) {
boolean success = folder.mkdir();
if (success){
file = new File(folder.getPath() + "/" + UUID.randomUUID(), toString()+ ".jpg");
}else {
Toast.makeText(FacialDetection.this, "Failed to save file to folder", Toast.LENGTH_SHORT).show();
}
}else{
file = new File(folder.getPath() + "/" + UUID.randomUUID(), toString()+ ".jpg");
}
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes() [0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
} catch (IOException e)
{
e.printStackTrace();
}
finally {
{
if (image != null)
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(***file***);
outputStream.write(bytes);
}finally {
if (outputStream != null)
outputStream.close();
}
}
};
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session, #NonNull CaptureRequest request, #NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(FacialDetection.this, "Saved " + ***file***, Toast.LENGTH_SHORT).show();
createCameraPreview();
}
};
The updated code, stuff bold and italic is what is throwing errors
I will advise you to create your own custom folder location this way:
File folder = new File(Environment.getExternalStorageDirectory() + "/CustomFolder");
File file;
if (!folder.exists()) {
boolean success = folder.mkdir();
if (success){
file = new File(folder.getPath() + "/" + UUID.randomUUID(), toString()+ ".jpg");
}else {
//Some message
}
}else {
file = new File(folder.getPath() + "/" + UUID.randomUUID(), toString()+ ".jpg");
}
//The rest of your code...
You're calling:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
I would speculate that .getExternalStoragePublicDirectory() means get directory on SD card. Is there a getInternal... method?
//Create folder !exist
String folderPath = Environment.getExternalStorageDirectory() +"/myFoldername";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdirs();
}
//create a new file
newFile = new File(folderPath, newPhoto.getName());
if (newFile != null) {
// save image here
Uri relativePath = Uri.fromFile(newFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, relativePath);
startActivityForResult(intent, CAMERA_REQUEST);
}

The image is nt getting converted into text.I am using tessOCR

I am building an app on OCR where the image is not getting converted in to the text.
TessOCR.java
public class TessOCR {
public static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/AndroidOCR/";
public static final String lang = "eng";
private static final String TAG = "TESSERACT";
private AssetManager assetManager;
private TessBaseAPI mTess;
Context context;
public TessOCR(AssetManager assetManager) {
Log.i(TAG, DATA_PATH);
this.assetManager = assetManager;
String[] paths = new String[]{"sdcard/tesseract/","sdcard/tesseract/" + "tessdata/"};
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(DATA_PATH + "tessdata/" + "eng.traineddata")).exists()) {
try {
InputStream in = assetManager.open("tessdata/" + "eng.traineddata");
OutputStream out = new FileOutputStream(new File(DATA_PATH + "tessdata/", lang + ".traineddata"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
}
public String getResults(Bitmap bitmap) {
mTess = new TessBaseAPI();
mTess.setDebug(true);
mTess.init("Environment.getExternalStorageDirectory().getPath()", "eng");
mTess.setImage(bitmap);
String result = mTess.getUTF8Text();
Intent intent = new Intent(context,Main2Activity.class);
context.startActivity(intent);
intent.putExtra(result,"key");
return result;
}
public void onDestroy() { mTess.end();
}
}
Main2Activity.java
mTessOCR = new TessOCR(assetManager);
processing1();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.call);
}
private void processing1() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TessOCR(assetManager);
Toast toast = Toast.makeText(Main2Activity.this, "SCANNing", Toast.LENGTH_LONG);
toast.show();
new TessOCR(assetManager).getResults(bitmap);
String value = getIntent().getExtras().getString("key");
TextView tv = (TextView) findViewById(R.id.tvv);
tv.setText(value);
Toast toast1 = Toast.makeText(Main2Activity.this, "SCANNED", Toast.LENGTH_LONG);
toast.show();
new TessOCR(assetManager).onDestroy();
//Intent intent = getIntent();
}
});
}
Logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.veena.cart_for_shopping, PID: 18124
java.lang.IllegalArgumentException: Data path does not exist!
at com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:305)
at com.googlecode.tesseract.android.TessBaseAPI.init(TessBaseAPI.java:282)
at com.example.veena.cart_for_shopping.TessOCR.getResults(TessOCR.java:70)
at com.example.veena.cart_for_shopping.Main2Activity$1.onClick(Main2Activity.java:62)
at android.view.View.performClick(View.java:4796)
at android.view.View$PerformClick.run(View.java:19920)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5383)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:939)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:734)
The app stops when I click on the button and the getResults() method is not able to bitmap image according to the logcat.
What's a solution for this?

setText in Android Studio & chronometer problems

I created an application that is used to download the files of a module that I have done! the application works well !. I'm trying to display the activity files that download from the FTP server in text view. But I am not able to display more than 3 messages. i create chronometer to, and when the apps download file, the chronometer STOP at 10 sec... and restart after downloaded all file at 2m30sec.... WHY ???
All message in start shift in IF condition is good... but all message in else doesnt work!
I NEED HELP PLEASE ... I post a part of my code and what i need to do.
Thx to all for reply!
Jira:
We have created an application for drillers. This application connects to a module to download files. Once the day is complete, the driller performs a Stop Shift. We want to display a message to the driller when he starts and stop his shift.
Action of StartShift 1017 - 1032
Action of StopShift 1035 - 1063
I created a textview to show at the user, the activity of the application.
The name of the textView: textViewDuration.
1 - We need to display the download of files in this textview.
At the line number 794 and 846 of the DashBoardActivity.java
Like: "Downloading: nameOfFile"
2 - We need to display the upload files name in this textview.
At line number 195, 265 and 329 of FtpMultiUploadTask.java
Like: "Uploading: nameOfFile"
I do not know why, I am able to display only 3 messages.
At line 1026 of DashBoardActivity ... textViewDuration.setText("Sending 'T' file");
and at line 1134 of DashBoardActivity ... textViewDuration.setText("Downloading all files ... Please Wait");
and reset to empty at line 1208 of DashBoardActivity ... textViewDuration.setText("");
Once the application shows this 3 messages, it does not display the others.
All setText i do on activity download, FtpMultiUpload or on stop shift does not work.
Line 1035, 1047, 1049, 1052, 1054, 1057 of DashBoardActivity.
I need help to change text of TextView when the download and upload of file as going on.
private void startShift() {
if (isToggleButtonChecked == (false)) {
writeLog(DashBoardActivity.this, "Version Unidrill: 0.3.13");
writeLog(DashBoardActivity.this, "Conn. Unibridge: " + UserPreferenceHelper.PREF_HOTSPOT);
writeLog(DashBoardActivity.this, "SSID: " + UserPreferenceHelper.getInstance(DashBoardActivity.this).getString(UserPreferenceHelper.getInstance(this).USER_ID + UserPreferenceHelper.PREF_SSID_NAME));
writeLog(DashBoardActivity.this, "START SHIFT");
//Toast.makeText(this , "Start Shift",Toast.LENGTH_LONG);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
textViewDuration.setText("Sending 'T' file");
indicateur.setVisibility(toggleButtonStart.VISIBLE);
isToggleButtonChecked = true;
toggleButtonStart.setText("STOP SHIFT");
UserPreferenceHelper.getInstance(this).saveString(UserPreferenceHelper.getInstance(this).USER_ID + UserPreferenceHelper.PREF_SHIFT_START, "true");
uniDrillApplication.runTaskModeDEMO();
} else {
/*
runOnUiThread(new Runnable() {
#Override
public void run() {
textViewDuration.setText("Downloading all files ... Please Wait");
}
});
*/
((TextView) findViewById(R.id.textViewDuration)).setText("STOP SHIFT");
//textViewDuration.setText("Downloading all files ... Please Wait");
UserPreferenceHelper.getInstance(this).saveString(UserPreferenceHelper.getInstance(this).USER_ID + UserPreferenceHelper.PREF_SHIFT_START, "false");
UserPreferenceHelper.getInstance(this).saveString(UserPreferenceHelper.getInstance(this).USER_ID + UserPreferenceHelper.PREF_IS_STOP_SHIFT, "0");
uniDrillApplication.is_downloaded = "0";
downloadFile();
this.textViewDuration.setText("");
SystemClock.sleep(5000);
uniDrillApplication.stopTask();
writeLog(DashBoardActivity.this, "STOP SHIFT");
writeLog(DashBoardActivity.this, "CREATE PDF REPORT");
textViewDuration.setText("Create Report PDF");
createPDF();
textViewDuration.setText("");
SystemClock.sleep(5000);
writeLog(DashBoardActivity.this, "PREPARING TO SEND MAIL");
textViewDuration.setText("Waiting wifi with internet");
sendMail();
textViewDuration.setText("Send Mail");
SystemClock.sleep(10000);
showProgress();
textViewDuration.setText("Sending file to FTP UNIDRAULIK");
sendFileToServer();
textViewDuration.setText("");
indicateur.setVisibility(toggleButtonStart.INVISIBLE);
isToggleButtonChecked = false;
toggleButtonStart.setText("START SHIFT");
mChronometer.stop();
mChronometer.setBase(SystemClock.elapsedRealtime());
}
}
private Boolean download(Context ctx, String server, int portNumber, String user, String password){
//this.textViewDuration.setText("Rendu dans le download");
((TextView) findViewById(R.id.textViewDuration)).setText("Debut du download!!!");
showProgress();
//toggleButtonStart.setText("Preparing to download file");
boolean success =false;
//dismissProgressDialog();
final Pattern PATTERN = Pattern.compile("(.*?)(?:\\((\\d+)\\))?(\\.[^.]*)?");
final Context _ctx = ctx;
String _server = server;
int _portNumber = portNumber;
String _user = user;
String _password = password;
final String UNIBRIDGE_FILE_PATH = "/mnt/myDrive";
String sdcardDestinationPath;
FTPClient ftpClient = new FTPClient();
List<String> _listFile = new ArrayList<>();
sdcardDestinationPath = Environment.getExternalStorageDirectory()+"/"+ this.getApplicationContext().getPackageName();
int TENSECONDS = 10*1000;
//showToast("DOWNLOADING ALL FILES! PLEASE WAIT ...");
//Toast.makeText(this, "Downloading ALL files! Please Wait!", Toast.LENGTH_LONG).show();
//if (toastTest != null){
// toastTest.cancel();
//}
//toastTest = Toast.makeText(this, "Preparing to download ALL files! Please Wait...", Toast.LENGTH_SHORT);
//toastTest.show();
try {
ftpClient.setControlEncoding("UTF-8");
ftpClient.setConnectTimeout(8000);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//showCustomPopup(GenericDialog.GenericDialogType.NONE, "Connexion to FTP UNIBRIDGE", null, null, null);
ftpClient.connect(_server, _portNumber);
writeLog(this,"Connexion to ftp unibridge ...");
boolean isConnected = ftpClient.login(_user, _password);
//prg.setProgress(15);
if (isConnected) {
writeLog(this,"Connexion to ftp unibridge = OK");
//showCustomPopup(GenericDialog.GenericDialogType.WARNING, "Connexion to FTP UNIBRIDGE = OK", null, null, null);
/*
//ALERTE AVEC TIMER A 2 SECONDES
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Connected to Unibridge FTP");
builder.setMessage("OK");
builder.setCancelable(true);
final AlertDialog dlg = builder.create();
dlg.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dlg.dismiss(); // when the task active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, 2000);
*/
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.printWorkingDirectory();
ftpClient.changeWorkingDirectory(UNIBRIDGE_FILE_PATH);
//showServerReply(_ctx);
FTPFile[] files = ftpClient.listFiles();
//prg.setProgress(20);
for (FTPFile file : files) {
final String fileName = file.getName();
//textViewDuration.setText("Checking file: " + fileName);
//Context baseCtx = getBaseContext();
//Context appCtx = getApplicationContext();
/*
DashBoardActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), fileName, Toast.LENGTH_LONG).show();
}
});
*/
//Toast.makeText(getBaseContext(), fileName, Toast.LENGTH_LONG).show();
/*
DashBoardActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), fileName, Toast.LENGTH_LONG).show();
}
});
**/
/*
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(DashBoardActivity.this, fileName, Toast.LENGTH_LONG).show();
}
});
*/
//Toast.makeText(this, file.getName(), Toast.LENGTH_LONG).show();
ftpClient.changeWorkingDirectory(UNIBRIDGE_FILE_PATH);
boolean verifFile = false;
String name = file.getName();
if (file.isDirectory()) {
//TODO : Vérifier pourquoi le fichier 700101 existe. Idéalement faire conditions contraire (if not en java)
if(!name.matches("\\d+(?:\\.\\d+)?") || (name.matches("700101"))) {
//return false;
}else{
writeLog(this, "current working directory : "+ftpClient.printWorkingDirectory());
writeLog(this, "change working directory to : " + name);
ftpClient.changeWorkingDirectory(name);
writeLog(this, "new working directory : "+ftpClient.printWorkingDirectory());
FTPFile[] unibridgeFiles = ftpClient.listFiles();
int i = 0;
for (FTPFile unibridgefile : unibridgeFiles) {
FTPFile[] fileDirectory = ftpClient.listFiles();
if(fileDirectory.length == 2){
writeLog(this, "Delete directory 1: "+ name);
writeLog(this, "___________________");
ftpClient.changeWorkingDirectory(UNIBRIDGE_FILE_PATH);
boolean checkDelete = ftpClient.removeDirectory(name);
}
if (! unibridgefile.isDirectory()) {
//download
OutputStream outputStream = null;
try {
writeLog(this, "LocalFilePath : " + sdcardDestinationPath);
writeLog(this, "File : " + unibridgefile.getName());
if(!".".equals(unibridgefile.getName()) && !"..".equals(unibridgefile.getName())){
if (unibridgefile.getName().contains(".csv")){
//String synchroFileName = "T"+ DateTools.getHours(this);
String synchroFileName = DateTools.getDateToString(new Date(),FORMAT_DATE_SYNCHRO);
System.out.println(synchroFileName);
String hh = "-" + synchroFileName.substring(6,8);
String date = synchroFileName.substring(0,6);
String checkShift = UserPreferenceHelper.getInstance(this).getString(UserPreferenceHelper.getInstance(this).USER_ID + UserPreferenceHelper.PREF_SHIFT_START);
if(checkShift.equals("true")){
if (unibridgefile.getName().contains("D") && unibridgefile.getName().contains(date) && unibridgefile.getName().contains(hh)){
}else if(unibridgefile.getName().contains("E") && unibridgefile.getName().contains(date)){
}else if(unibridgefile.getName().contains("R") && unibridgefile.getName().contains(date)){
}else{
//Toast.makeText(getApplicationContext(), "Downloading: 00000000" , Toast.LENGTH_LONG).show();
//SystemClock.sleep(2000);
File _file = new File(sdcardDestinationPath, unibridgefile.getName());
FileOutputStream destFileStream = new FileOutputStream(_file);
//if (toastTest != null){
// toastTest.cancel();
//}
//toastTest = Toast.makeText(getBaseContext(), "Downloading: " + unibridgefile.getName(), Toast.LENGTH_SHORT);
//toastTest.show();
outputStream = new BufferedOutputStream(destFileStream);
/*
HERE WE NEED MESSAGE TO SHOW EACH FILE IS DOWNLOADING
*/
ftpClient.retrieveFile(unibridgefile.getName(), outputStream);
final String nameFile = unibridgefile.getName();
//Toast.makeText(getApplicationContext(),"Your message",Toast.LENGTH_LONG).show();
//toast.setText("Downloading: " + nameFile);
//toast.setDuration(Toast.LENGTH_LONG);
//toast.show();
/*
Runnable changeText =
new Runnable() {
#Override
public void run() {
Toast.makeText(DashBoardActivity.this, "Downloading: " + nameFile, Toast.LENGTH_SHORT).show();
}
};
runOnUiThread(changeText);
*/
/*
final Handler handler= new Handler();
final Runnable r = new Runnable() {
public void run() {
Toast.makeText(DashBoardActivity.this, "Downloading: " + nameFile, Toast.LENGTH_SHORT).show();
//handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 5);
*/
/*
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Downloading: " + nameFile,Toast.LENGTH_SHORT).show();
}
});
*/
boolean deletefile = ftpClient.deleteFile(unibridgefile.getName());
}
}else{
File _file = new File(sdcardDestinationPath, unibridgefile.getName());
FileOutputStream destFileStream = new FileOutputStream(_file);
outputStream = new BufferedOutputStream(destFileStream);
/*
HERE WE NEED MESSAGE TO SHOW EACH FILE IS DOWNLOADING
*/
ftpClient.retrieveFile(unibridgefile.getName(), outputStream);
//Handler handler = new Handler(Looper.getMainLooper());
//handler.post(new Runnable() {
// #Override
// public void run() {
// Toast.makeText(DashBoardActivity.this.getApplicationContext(),"Downloading: tesssst",Toast.LENGTH_SHORT).show();
// }
//});
boolean deletefile = ftpClient.deleteFile(unibridgefile.getName());
textViewDuration.setText("");
/*
_listFile.add(unibridgefile.getName());
writeLog(_ctx,"Download file :" + unibridgefile.getName() + " in progress.");
String fileName = "";
File _file = new File(sdcardDestinationPath, unibridgefile.getName());
Matcher m = PATTERN.matcher(unibridgefile.getName());
if (m.matches()) {
String prefix = m.group(1);
String last = m.group(2);
String suffix = m.group(3);
if (suffix == null) suffix = "";
int count = 0;
while(_file.exists()) {
count++;
fileName = prefix + "(" + count + ")" + suffix;
_file = new File(sdcardDestinationPath, fileName);
verifFile = true;
}
}
FileOutputStream destFileStream = new FileOutputStream(_file);
outputStream = new BufferedOutputStream(destFileStream);
success = ftpClient.retrieveFile(unibridgefile.getName(), outputStream);
if (verifFile){
String line = "";
BufferedReader br = new BufferedReader(new FileReader(sdcardDestinationPath + "/" + fileName));
br.readLine();
FileWriter fw = new FileWriter(sdcardDestinationPath + "/" + unibridgefile.getName(), true);
while((line = br.readLine()) != null){
fw.append(line + "\n");
}
fw.flush();
fw.close();
br.close();
_file.delete();
}
if(success){
//writeLog(_ctx, unibridgefile.getName()+" downloaded to "+ sdcardDestinationPath);
String deleteFilePath = ftpClient.printWorkingDirectory() + "/" + unibridgefile.getName();
//boolean test = ftpClient.deleteFile(deleteFilePath);
//System.out.println(test);
boolean deletefile = ftpClient.deleteFile(unibridgefile.getName());
FTPFile[] fileDirectory2 = ftpClient.listFiles();
if(fileDirectory2.length == 2){
ftpClient.changeWorkingDirectory(UNIBRIDGE_FILE_PATH);
boolean checkDelete = ftpClient.removeDirectory(name);
writeLog(_ctx, "Delete directory: "+ name);
writeLog(_ctx, "____________________ ");
}
}else{
writeLog(_ctx, unibridgefile.getName()+" not downloaded to "+ sdcardDestinationPath);
}
*/
}
}
}
} finally {
if (outputStream != null) {
outputStream.close();
}
}
}
}
writeLog(this, "current working directory : "+ftpClient.printWorkingDirectory());
writeLog(this, "change working directory to parent ");
ftpClient.changeToParentDirectory();
writeLog(this, "new working directory : "+ftpClient.printWorkingDirectory());
/* if(success){
int test = ftpClient.dele(ftpClient.printWorkingDirectory());
System.out.println(test);
boolean delete = ftpClient.deleteFile(ftpClient.printWorkingDirectory());
System.out.println(delete);
}*/
}
}
}
if (ftpClient.isConnected()){
ftpClient.disconnect();
}
dismissProgressDialog();
return success;
} else {
dismissProgressDialog();
writeLog(this, "Connexion to ftp unibridge = KO");
return false;
}
} catch (Exception e) {
Log.d("FTP", e.toString());
writeLog(this, "Exception ="+ e.toString());
// return false;
success =false;
}finally {
//if the IO is timed out or force disconnected, exceptions may be thrown when trying to logout/disconnect
try
{
ftpClient.setSoTimeout(TENSECONDS);
ftpClient.logout();
}
catch(Exception innerException)
{
success = false;
}
finally
{
try {
ftpClient.disconnect();
}catch (IOException ex){
ex.printStackTrace();
}
success = false;
}
}
textViewDuration.setText("");
return success;
}
Pic #1: this is when i open app
Pic #2: When i press Start Shift... the textView change ... but the chrono stay to 0!
Pic #3: The chrono start at 0:05, and the text change... but i wan't show to user the name of file ... not a please wait :)
Pic #4: When all file is downloded, the text view dissapear ... and i press stop shift, but the text view never show again and the chrono stop
Pic #5: After all task are done, the chrono is reset to 0, and ready to start other shift!

Images are not Showing in Gallery even after scanning using MediaScannerConnection.scanFile()

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

How clear gallery thumbnails after deleting image from DCIM in Android

I am deleting image after capture and doing some work on it.But after deleting the image Gallery till hold the thumbnails. How clear gallery thumbnails after deleting image from DCIM in Android.
private boolean deleteLastFromDCIM() {
boolean success = false;
try {
File[] images = new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM"+File.separator+"Camera").listFiles();
File latestSavedImage = images[0];
for (int i = 1; i < images.length; ++i) {
if (images[i].lastModified() > latestSavedImage.lastModified()) {
latestSavedImage = images[i];
}
}
// OR JUST Use success = latestSavedImage.delete();
success = new File(Environment.getExternalStorageDirectory()
+ File.separator + "DCIM/Camera/"
+ latestSavedImage.getAbsoluteFile()).delete();
return success;
} catch (Exception e) {
e.printStackTrace();
return success;
}}
if(file.exists()){
Calendar time = Calendar.getInstance();
time.add(Calendar.DAY_OF_YEAR,-7);
//I store the required attributes here and delete them
Date lastModified = new Date(file.lastModified());
if(lastModified.before(time.getTime()))
{
//file is older than a week
}
file.delete();
}else{
file.createNewFile();
}
Just you need to write a method for delete file and replace the code file.delete(); with deleteFileFromMediaStore(this.getContentResolver(),file);
public void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
}
}
}

Categories

Resources