Android UI not updating - java

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

Related

Video Compression library in Java android? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
I am using Silicompressor library for video compression.
My video size is 15 MB and compressed video size is coming to 500 kb
since the compressed size is very very small and when clicked on play button of compressed video it shows an error as "Failed to play video."
How do I get a compressed size in MB?
Here is my code after compressing
File imageFile = new File(compressedFilePath);
float length = imageFile.length() / 1024f; // Size in KB
System.out.println("length = " + length);
String value;
if (length >= 1024)
value = length / 1024f + " MB";
else
value = length + " KB";
Any other alternative library which works well for video compression ?
you can use LightCompressor library
LightCompressor
call compressVideo class and pass to it the video path and the desired compressed video location
selectedVideo = data.getData();
compressVideo(getMediaPath(QabaelAdd.this,selectedVideo));
fpath=saveVideoFile(QabaelAdd.this,path).getPath(); //the compressed video location
private static File saveVideoFile(Context context, String filePath) throws IOException {
if (filePath != null) {
File videoFile = new File(filePath);
String videoFileName = "" + System.currentTimeMillis() + '_' + videoFile.getName();
String folderName = Environment.DIRECTORY_MOVIES;
if (Build.VERSION.SDK_INT < 30) {
File downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File desFile = new File(downloadsPath, videoFileName);
if (desFile.exists()) {
desFile.delete();
}
try {
desFile.createNewFile();
} catch (IOException var61) {
var61.printStackTrace();
}
return desFile;
}
ContentValues var10 = new ContentValues();
boolean var11 = false;
boolean var12 = false;
var10.put("_display_name", videoFileName);
var10.put("mime_type", "video/mp4");
var10.put("relative_path", folderName);
var10.put("is_pending", 1);
ContentValues values = var10;
Uri collection = MediaStore.Video.Media.getContentUri("external_primary");
Uri fileUri = context.getContentResolver().insert(collection, values);
Void var10000;
if (fileUri != null) {
boolean var13 = false;
Closeable var18 = (Closeable)context.getContentResolver().openFileDescriptor(fileUri, "rw");
boolean var19 = false;
boolean var20 = false;
Throwable var73 = (Throwable)null;
try {
ParcelFileDescriptor descriptor = (ParcelFileDescriptor)var18;
if (descriptor != null) {
boolean var24 = false;
boolean var25 = false;
Closeable var28 = (Closeable)(new FileOutputStream(descriptor.getFileDescriptor()));
boolean var29 = false;
boolean var30 = false;
Throwable var74 = (Throwable)null;
try {
FileOutputStream out = (FileOutputStream)var28;
Closeable var33 = (Closeable)(new FileInputStream(videoFile));
boolean var34 = false;
boolean var35 = false;
Throwable var76 = (Throwable)null;
try {
FileInputStream inputStream = (FileInputStream)var33;
byte[] buf = new byte[4096];
while(true) {
int sz = inputStream.read(buf);
if (sz <= 0) {
Unit var77 = Unit.INSTANCE;
break;
}
out.write(buf, 0, sz);
}
} catch (Throwable var62) {
var76 = var62;
throw var62;
} finally {
//CloseableKt.closeFinally(var33, var76);
}
Unit var75 = Unit.INSTANCE;
} catch (Throwable var64) {
var74 = var64;
throw var64;
} finally {
//CloseableKt.closeFinally(var28, var74);
}
Unit var72 = Unit.INSTANCE;
} else {
var10000 = null;
}
} catch (Throwable var66) {
var73 = var66;
throw var66;
} finally {
//CloseableKt.closeFinally(var18, var73);
}
values.clear();
values.put("is_pending", 0);
context.getContentResolver().update(fileUri, values, (String)null, (String[])null);
return new File(QabaelAdd.getMediaPath(context, fileUri));
}
var10000 = (Void)null;
}
return null;
}
#NotNull
public static String getMediaPath(#NotNull Context context, #NotNull Uri uri) throws IOException {
Intrinsics.checkNotNullParameter(context, "context");
Intrinsics.checkNotNullParameter(uri, "uri");
ContentResolver resolver = context.getContentResolver();
String[] projection = new String[]{"_data"};
Cursor cursor = (Cursor)null;
String var30;
try {
File file;
String var57;
try {
cursor = resolver.query(uri, projection, (String)null, (String[])null, (String)null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow("_data");
cursor.moveToFirst();
var57 = cursor.getString(columnIndex);
Intrinsics.checkNotNullExpressionValue(var57, "cursor.getString(columnIndex)");
} else {
var57 = "";
}
return var57;
} catch (Exception var53) {
String filePath = context.getApplicationInfo().dataDir + File.separator + System.currentTimeMillis();
file = new File(filePath);
InputStream var10000 = resolver.openInputStream(uri);
if (var10000 != null) {
Closeable var13 = (Closeable)var10000;
InputStream inputStream = (InputStream)var13;
Closeable var18 = (Closeable)(new FileOutputStream(file));
FileOutputStream outputStream = (FileOutputStream)var18;
byte[] buf = new byte[4096];
while(true) {
int var25 = inputStream.read(buf);
if (var25 <= 0) {
break;
}
outputStream.write(buf, 0, var25);
}
}
}
var57 = file.getAbsolutePath();
Intrinsics.checkNotNullExpressionValue(var57, "file.absolutePath");
var30 = var57;
} finally {
if (cursor != null) {
cursor.close();
}
}
return var30;
}
private void compressVideo(String path){
VideoCompressor.start(path,fpath , new CompressionListener() {
#Override
public void onStart() {
// Compression start
}
#Override
public void onSuccess() {
// On Compression success
Uri uploadUri = Uri.fromFile(new File(fpath));
Log.e("is dir", String.valueOf(new File(fpath).isDirectory()));
uploadVideoMethod(uploadUri); //upload the video
}
#Override
public void onFailure(String failureMessage) {
// On Failure
Log.e("fail", failureMessage);
Toast.makeText(QabaelAdd.this, "failed to compress video", Toast.LENGTH_LONG).show();
}
#Override
public void onProgress(float v) {
// Update UI with progress value
runOnUiThread(new Runnable() {
public void run() {
progressDialog.setMessage(" جاري تهيئة الفيديو "+String.valueOf(Math.round(v))+"%");
Log.e("progress", String.valueOf(v));
}
});
}
#Override
public void onCancelled() {
// On Cancelled
}
}, VideoQuality.MEDIUM, false, false);
}
Can you go with SiliCompressor. It's nice and simple library and give good result. I have used it.
Try to implement this. If you get any error let me know.
https://github.com/Tourenathan-G5organisation/SiliCompressor
Edit:
This way you can call the async task.
class VideoCompressAsyncTask extends AsyncTask<String, String, String> {
Context mContext;
public VideoCompressAsyncTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... paths) {
String filePath = null;
try {
filePath = SiliCompressor.with(mContext).compressVideo(paths[0], paths[1]);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return filePath;
}
#Override
protected void onPostExecute(String compressedFilePath) {
super.onPostExecute(compressedFilePath);
File videoFile = new File(compressedFilePath);
}
}
Then now call it.
new VideoCompressAsyncTask(getActivity()).execute(selectedVideoPath, f.getPath());
selectedVideoPath is the video source path and f.getPath() is the destination path.
Try this way.

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!

duplicate contacts as vcf file android

I found this code around the forum for creating a vcf file with all contacts stored in the phone. well i get all contacts but duplicate does anyone know how to fix it? i am only interested in the contacts displayed in the contacts book not google contacts etc. THANKS
private void getVcardString() throws IOException {
// TODO Auto-generated method stub
//ProgressBar pro = (ProgressBar)findViewById(R.id.pb);
// ProgressBar pro = (ProgressBar) findViewById(R.id.pb1);
vCard = new ArrayList<String>(); // Its global....
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1",
null, null, null);
if (cursor != null && cursor.getCount() > 0) {
int i;
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
cursor.moveToFirst();
for (i = 0; i < cursor.getCount(); i++) {
get(cursor);
Log.d("TAG", "Contact " + (i + 1) + "VcF String is" + vCard.get(i));
cursor.moveToNext();
mFileOutputStream.write(vCard.get(i).toString().getBytes());
}
mFileOutputStream.close();
cursor.close();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
tx.setText("");
pro.setVisibility(View.GONE);
btn3.setVisibility(View.VISIBLE);
tx1.setVisibility(View.VISIBLE);
Toast toast=Toast.makeText(getApplicationContext(),"בוצע גיבוי לכרטיס הזיכרון",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0,90);
toast.show();
}
});
} else {
Log.d("TAG", "No Contacts in Your Phone");
}
}
private void get(Cursor cursor2) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring = new String(buf);
vCard.add(vcardstring);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
} here
just found the solution edit query:
getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

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!!

Categories

Resources