setText in Android Studio & chronometer problems - java

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!

Related

Save an Image with TextureView?

I hope you can fix my problem:
I have got a textureview to takes photos but when he capture photos, the file who need to contain the picture is empty. I don't know where and what is the problem. I just think that the problem is when the file is created. Thank you to help me.
This is a part of my code :
private void takePicture() throws CameraAccessException, IOException {
if(cameraDevice == null){
return;
}
CameraManager manager = (CameraManager) Objects.requireNonNull(getContext()).getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
int width = 640;
int height = 480;
if(jpegSizes!=null && jpegSizes.length>0){
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width,height, ImageFormat.JPEG, 1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(reader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE,CameraMetadata.CONTROL_MODE_AUTO);
int rotation = Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));
// First I get the path to gallery and crate new Album to my app
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
mImageFolder = new File(file, "Fluico");
if (!mImageFolder.exists()) {
if (!mImageFolder.mkdirs()) {
Log.d("Fluicophoto", "failed to create directory");
}
}
/*Second I cut mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
from onActivityCreated and add here with the new path from my Album*/
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "IMAGE_" + timestamp + "_";
file = File.createTempFile(prepend, ".jpg", mImageFolder);
Toast.makeText(getContext(), "file need to be save", Toast.LENGTH_SHORT).show();
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
try {
save(bytes);
} finally {
image.close();
}
}
};
reader.setOnImageAvailableListener(readerListener,mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(getContext(), "saved", Toast.LENGTH_SHORT).show();
try{
createCameraPreview();
}catch (CameraAccessException e){
Toast.makeText(getContext(), "capture not comleted", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured( CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
Toast.makeText(getContext(), "capture not configured", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConfigureFailed( CameraCaptureSession session) {
}
},mBackgroundHandler);
}
private void save(byte[] bytes) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.close();
Toast.makeText(getContext(), "it's good", Toast.LENGTH_SHORT).show();
}catch (IOException e){
Toast.makeText(getContext(), "file not found", Toast.LENGTH_SHORT).show();
}
}
Try with below code:
File myDir;
String fname;
String id = "123456";
int count = 0;
String root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/PhotoApp/" + id);
myDir.mkdirs();
count++;
counter.setText(String.valueOf(count));
fname = "" + id + "-" + count + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
This code will create a folder PhotoApp and inside the folder, all the images will store.
You can get full code with the camera in my GitHub:
Link: https://github.com/abhishekhzb/quick_camera

Android Save Video To Gallery

I am developing app using camera on fragment,so for camera I have used this library https://natario1.github.io/CameraView/home because I am using watermarks in camera, now I want to save pictures and videos to gallery, for pictures I have done with below code, for video I done research but not get a solution, for pictures this library is giving bitmap so pictures are saving perfectly but for video I can't figure out kindly help me.
Thank you
public class VideoPreviewActivity extends AppCompatActivity {
private VideoView videoView;
private static VideoResult videoResult;
private Button btnSaveVideo;
public static void setVideoResult(#Nullable VideoResult result) {
videoResult = result;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_preview);
final VideoResult result = videoResult;
if (result == null) {
finish();
return;
}
btnSaveVideo = findViewById(R.id.save_video);
videoView = findViewById(R.id.video);
videoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playVideo();
}
});
AspectRatio ratio = AspectRatio.of(result.getSize());
MediaController controller = new MediaController(this);
controller.setAnchorView(videoView);
controller.setMediaPlayer(videoView);
videoView.setMediaController(controller);
videoView.setVideoURI(Uri.fromFile(result.getFile()));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
ViewGroup.LayoutParams lp = videoView.getLayoutParams();
float videoWidth = mp.getVideoWidth();
float videoHeight = mp.getVideoHeight();
float viewWidth = videoView.getWidth();
lp.height = (int) (viewWidth * (videoHeight / videoWidth));
videoView.setLayoutParams(lp);
playVideo();
if (result.isSnapshot()) {
// Log the real size for debugging reason.
Log.e("VideoPreview", "The video full size is " + videoWidth + "x" + videoHeight);
}
}
});
//Click this button to save video
btnSaveVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Calling 1st Method but not working
//SaveVideo(videoResult.getFile().toString());
//2nd method calling but still not working
saveVideoToInternalStorage(videoResult.getFile().toString());
}
});
}
void playVideo() {
if (!videoView.isPlaying()) {
videoView.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!isChangingConfigurations()) {
setVideoResult(null);
}
}
//first method which I tried but not working
private void SaveVideo(Uri f) {
//I don't know what data type I have to pass in the methods parameters
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath();
File myDir = new File(root + "/Push Videos");
if (!myDir.exists()) {
myDir.mkdirs();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Video-"+ n +".mp4";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
Toast.makeText(VideoPreviewActivity.this, "PUSH Video Saved", Toast.LENGTH_LONG).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//Tried this 2nd method but it is also not giving a desired result
//For saving Video...
private void saveVideoToInternalStorage (String filePath) {
File newfile;
try {
File currentFile = new File(filePath);
String fileName = currentFile.getName();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("videoDir", Context.MODE_PRIVATE);
newfile = new File(directory.getAbsolutePath(), fileName);
if(currentFile.exists()){
InputStream in = new FileInputStream(currentFile);
OutputStream out = new FileOutputStream(newfile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
scanner(filePath);
in.close();
out.close();
Log.v("", "Video file saved successfully.");
Toast.makeText(this, "Push Video Saved TO Gallery", Toast.LENGTH_SHORT).show();
}else{
Log.v("", "Video saving failed. Source file missing.");
}
} catch (Exception e) {
Log.d("Err ", "EXS " + e.getMessage());
e.printStackTrace();
}
}
}

AWS Unable to calculate MD5 hash Android

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.

Difference between triggering camera.take picture from button click[Working] and through function call[Not working]

I am stuck at this. MY application clicks multiple images programmatically.
Issue is my take picture call is inside button listener click function.
1. When i do button click it triggers the thread for take picture that works.
2. If i directly call that obj.run() it does not-> shows take picture failed at run time.
3. If i do btn.perform click - still fails.
I am building an application that listens on a socket and on a trigger click multiple images n save them to create .gif.
code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// android.support.v7.appcompat.R.layout.activity_main;
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
myContext = this;
initialize();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
// mCamera.Parameters.class.
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
capture.performClick();
Log.d("naval", "onresume- clicked performed");
}
}
public void initialize() {
cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (Button) findViewById(R.id.button_capture);
// capture.setVisibility(View.GONE);
capture.setOnClickListener(captrureListener);
// capture.performClick();
switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
switchCamera.setVisibility(View.GONE); // JUST CHANGE THIS TO MAKE SWITCH CAMERA WORKS
switchCamera.setOnClickListener(switchCameraListener);
Log.d("naval", "initialize");
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
//if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
Log.d("naval", "onpause");
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//make a new picture file
File pictureFile = getOutputMediaFile();
Log.d("naval", "picture call back start");
if (pictureFile == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.d("naval", "picture call back stream creation");
fos.write(data);
fos.close();
Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
Log.d("naval", "picture call back toast");
toast.show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
//cameraPreview.start();
}
};
return picture;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
try {
Thread.sleep(1000);
}catch (Exception e)
{
e.printStackTrace();
}
CaptureThread captureThread = new CaptureThread();
captureThread.start();
/* String str = "";
while(true)
{
Log.d("naval","waiting for start inside file loop");
str = readFromFile();
if(str.equals("start")) {
Log.d("naval","calling capture object");
str = "";
CaptureThread captureThread = new CaptureThread();
captureThread.start();
}
else
{
try {
Log.d("naval","sleeping inside str loop");
Thread.sleep(1000);
}catch(Exception e)
{
e.printStackTrace();
}
continue;
// put sleep here
}
// read text file here at location /sdcard/info/info.txt
}*/
}
};
private String readFromFile() {
String ret = "";
try {
FileInputStream fis = new FileInputStream (new File("/storage/emulated/0/info/info.txt")); // 2nd line
// InputStream inputStream = openFileInput("/storage/emulated/0/info/info.txt");
if ( fis != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
fis.close();
ret = stringBuilder.toString();
Log.d("naval- string",ret);
if(!ret.isEmpty())
{
Log.d("naval","str is not null");
//delete file or clear file and create one
File fil = new File("/storage/emulated/0/info/info.txt");
fil.delete();
// create
File file = new File("/storage/emulated/0/info/info.txt");
file.createNewFile();
}
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
//make picture and save to a folder
private static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "pics");
Log.d("naval", "save picture function");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
Log.d("naval", "cave picture betweent");
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "pic" + glo + ".png");
Log.d("naval", "File path above");
glo++;
return mediaFile;
}
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
class CaptureThread extends Thread {
#Override
public void run() {
int count = 0;
while(count < 6) {
**mCamera.takePicture(null, null, mPicture);**
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
createGif();
}
public void createGif()
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 6;
encoder.setDelay(100);
encoder.start(bos);
for(int i = 0;i<6;i++){
Bitmap bMap = BitmapFactory.decodeFile("/storage/emulated/0/pics/pic"+i+".png",options);
Log.d("naval","added image");
encoder.addFrame(bMap);
}
encoder.finish();
writeToFile(bos.toByteArray());
}
public void writeToFile(byte[] array) {
try {
String path = Environment.getExternalStorageDirectory() + "/gif/gif.gif";
FileOutputStream stream = new FileOutputStream(path);
stream.write(array);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
ok the answer is from button click it comes from UI thread. But the function call does not. to run this call the function from UI thread . It will work!!

Android UI not updating

I am currently creating a program that recursively searches through the SD card of the videos on an android phone, and then produces as hash for each of the videos.
Everything works fine, but when I try and create a progress bar, the progress bar doesn't update, until the end.
So essentially progress bar's progress appears to go from 0 to the max, but I can tell from log output that values are being sent to the progress bar to update it, the progress bar just isn't upating.
My code is below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
text = (TextView) findViewById(R.id.tv1);
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
recursiveVideoFinder(new File("/sdcard"));
String strDB3File = getFilesDir().getPath()
+ "/VideoHashes.db3";
sql3 = SQLiteDatabase.openDatabase(strDB3File, null,
SQLiteDatabase.CREATE_IF_NECESSARY);
try {
String mysql = "CREATE TABLE videohashes (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, path TEXT NOT NULL, hash TEXT NOT NULL, date TEXT NOT NULL, size INTEGER)";
sql3.execSQL(mysql);
} catch (SQLiteException e) {
// TODO: handle exception
}
progress.setProgress(0);
progress.setMax(myFiles.size());
for (String path : myFiles) {
try {
String hash = getMD5Checksum(path);
ContentValues myInsertData = new ContentValues();
myInsertData.put("path", path);
myInsertData.put("hash", hash);
Date date = new Date();
myInsertData.put("date", dateFormat.format(date));
myInsertData.put("size", getFileSize(path));
sql3.insert("videohashes", null, myInsertData);
currVid++;
updateProgress();
Log.i("Progress", "CurrVid:" + currVid + " Max:"
+ progress.getMax());
text.append(currVid + " ");
} catch (Exception e) {
Log.i("File", "File not Found");
}
}
Cursor cur = sql3.query("videohashes", null, null, null, null,
null, null);
cur.moveToFirst();
while (!cur.isAfterLast()) {
/*
* ((TextView) findViewById(R.id.tv1)).append("\n" +
* cur.getString(1) + "\n" + cur.getString(2) + "\n" +
* cur.getString(3) + "\n" + cur.getString(4) + "\n");
*/
cur.moveToNext();
}
cur.close();
}
});
}
public long getFileSize(String path) {
File file = new File(path);
return file.length();
}
private void recursiveVideoFinder(File _dir) {
File[] files = _dir.listFiles();
if (files == null) {
return;
}
for (File currentFile : files) {
if (currentFile.isDirectory()) {
recursiveVideoFinder(currentFile);
continue;
} else {
for (String aEnd : getResources().getStringArray(
R.array.VideoExtensions)) {
if (currentFile.getName().endsWith(aEnd)) {
Log.d("PS:", currentFile.getPath().toString());
String videoFileName = currentFile.getPath().toString();
myFiles.add(videoFileName);
}
}
}
}
}
// Code based off this example:
// http://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java
public static byte[] createCheckSum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
// Return MD5 Hash
return complete.digest();
}
public String getMD5Checksum(String filename) throws Exception {
byte[] b = createCheckSum(filename);
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public void updateProgress() {
progress.setProgress(currVid);
progress.invalidate();
Log.i("Updating", "Updating Progress Bar");
}
}
Why do you keep all the processing code in Onclick(). That is not a good approach. Create an AsyncTask and use publishProgress to update your progressbar.
Put your updating task by overriding onResume(). Start a new timer thread there and keep calling your function. When you click back, finish that thread too by saying timer.cancel(). SO whenever you go that activity, only then the timer starts and exits on hitting back. Check this for more info

Categories

Resources