I am trying to write the results of my program in a file but i do not know why its does not write nothing.
I have done a program and it creates a file but when I open the file, it is empty. What i have done wrong?
MongoClient mongoClient;
DB db;
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("behaviourDB_areas");
DBCollection cEvent = db.getCollection("events_Searching");
File file = new File ("C:\\Users\\Nikos\\Documents\\Apotelesmata\\file1.txt");
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter (file);
BasicDBObject orderBy = new BasicDBObject();
orderBy.put("timeStamp",1);
DBCursor cursorEvents = null;
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("user_id", "55b20db905f333defea9827f");
cursorEvents = cEvent.find(searchQuery).sort(orderBy);
int count = 1;
int start = 1;
String timeStartOld = null;
while (cursorEvents.hasNext()) {
DBObject documentInEventCollection = cursorEvents.next();
if("pageLoad".equals(documentInEventCollection.get("type"))){
writer.println("URL(" + count + "): " + documentInEventCollection.get("url").toString());
//System.out.println("time-start(" + start + "): " + documentInEventCollection.get("timeStamp").toString());
count++;
start++;
try {
String timeStart = (documentInEventCollection.get("timeStamp").toString());
if(timeStartOld==null){
timeStartOld = timeStart;
continue;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-dd-MM;HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(timeStartOld);
d2 = format.parse(timeStart);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
writer.println(diffDays + " days, ");
writer.println(diffHours + " hours, ");
writer.println(diffMinutes + " minutes, ");
writer.println(diffSeconds + " seconds.");
timeStartOld = timeStart;
} catch (Exception e) {
e.printStackTrace();
}
}
writer.close();
}
mongoClient.close();
Thank you for your answer.
Try if the below statement is getting printed in console.
System.out.println("time-start(" + start + "): " + documentInEventCollection.get("timeStamp").toString());
If not, execution is not entering the below if statement. Try some conditions where the if gets true.
if("pageLoad".equals(documentInEventCollection.get("type"))){ ...
Related
I'm trying to make a countdown in days, hours, minutes, seconds from a starting date and I'm getting the days wrong for some reason I cannot find.
String givenDateString = "2019-05-15T09:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
new CountDownTimer(timeInMilliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long day = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
millisUntilFinished -= TimeUnit.DAYS.toMillis(day);
long hour = TimeUnit.MILLISECONDS.toHours(millisUntilFinished);
millisUntilFinished -= TimeUnit.HOURS.toMillis(hour);
long minute = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
millisUntilFinished -= TimeUnit.MINUTES.toMillis(minute);
long second = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);
prueba.setText("Days: "+day+" Hours: "+hour+" Minutes: "+minute+" Seconds: "+second);
}
#Override
public void onFinish() {
// What ever you want !
}
}.start();
And I'm getting this result:
New error android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
TextView prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prueba = findViewById(R.id.prueba);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date currentDate = null;
Date destinationDate = null;
try {
currentDate = Calendar.getInstance().getTime();
destinationDate = sdf.parse("2019-05-15T09:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
calculateDifference(currentDate, destinationDate);
}
}, 0, 1000);//Update text every second
}
public void calculateDifference(Date startDate, Date endDate) {
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long days = different / daysInMilli;
different = different % daysInMilli;
long hours = different / hoursInMilli;
different = different % hoursInMilli;
long minutes = different / minutesInMilli;
different = different % minutesInMilli;
long seconds = different / secondsInMilli;
Log.e("calculation", "Days: " + days + " Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
prueba.setText("Days: " + days + " Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
}
Hello there here is how you can achieve this
Here is the method which calculate the difference between two date.
public void calculateDifference(Date startDate, Date endDate) {
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long days = different / daysInMilli;
different = different % daysInMilli;
long hours = different / hoursInMilli;
different = different % hoursInMilli;
long minutes = different / minutesInMilli;
different = different % minutesInMilli;
long seconds = different / secondsInMilli;
Log.e("calculation", "Days: " + days + " Hours: " + hours + " Minutes: " + minutes + " Seconds: " + seconds);
}
You can settext of you text view instead of log
And this is how you can call the timer with date
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date currentDate = null;
Date destinationDate = null;
try {
currentDate = Calendar.getInstance().getTime();
destinationDate = sdf.parse("2019-05-15T09:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
calculateDifference(currentDate, destinationDate);
}
}, 0, 1000);//Update text every second
}
I've been implementing an app, and was doing a DAO class with a function, which would return all events on current day. But, I have a small bug. For example: we have 2 events - event1(02:00-03:00) and event2(14:00-16:00). And we want event1 to be the first in the row. Okay, we have implemented a sort which does it, but! event2 is 1516024800000 ms and event1 is 1542618000000.
I know that to give u a working sample would be helpful, but i am not able to...
Here is this function:
public List<Schedule> getScheduleByDate(int year, int month, int day, String Account) {
List<Schedule> schedules = new ArrayList<>();
List<CalendarClass> calendarClasses = mCalendarClassDao.getTrueCalendars();
/*if(Account.equals("ANONYMOUS")){
return schedules;
}*/
String[] INSTANCE_PROJECTION = new String[]{
CalendarContract.Instances.CALENDAR_ID, // 0
CalendarContract.Instances.TITLE, // 1
CalendarContract.Instances.DESCRIPTION,
CalendarContract.Instances.DTSTART,
CalendarContract.Instances.DTEND,
CalendarContract.Instances.DISPLAY_COLOR,
CalendarContract.Instances.EVENT_COLOR,
CalendarContract.Instances.EVENT_COLOR_KEY,
CalendarContract.Instances.ALL_DAY,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.OWNER_ACCOUNT,
CalendarContract.Instances.RRULE,
CalendarContract.Instances.ORIGINAL_INSTANCE_TIME
};
Calendar startTime = Calendar.getInstance();
startTime.set(year, month, day, 0, 0, 0);
long time = startTime.getTimeInMillis();
//time -= 1000;
//end fix
Calendar endTime = Calendar.getInstance();
endTime.set(year, month, day, 23, 59, 59);
long endMillis = endTime.getTimeInMillis();
for (int i = 0; i < calendarClasses.size(); ++i) {
//String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + time + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + endTime.getTimeInMillis() + " ) AND ( " + CalendarContract.Events.CALENDAR_ID + " = " + "'" + calendarClasses.get(i).getId() + "'" + " ))";
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.READ_CALENDAR}, 1000);
}
String selection = CalendarContract.Instances.CALENDAR_ID + " = " + "'" + calendarClasses.get(i).getId() + "'";
//Cursor cursor = mContext.getContentResolver().query(CalendarContract.Events.CONTENT_URI, projection, selection, null, null);
// sort
Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, time);
ContentUris.appendId(builder, endMillis);
Cursor cursor = mContext.getContentResolver().query(builder.build(),
INSTANCE_PROJECTION,
selection,
null,
CalendarContract.Instances.DTSTART);
while (cursor.moveToNext()){
Log.wtf("1", "1");
Schedule schedule = new Schedule();
schedule.setTitle(cursor.getString(1));
schedule.setDesc(cursor.getString(2));
schedule.setTime(cursor.getLong(3));
schedule.setTime_end(cursor.getLong(4));
schedule.setColor(cursor.getInt(5));
schedule.setLocation(cursor.getString(9));
schedule.setAccount(cursor.getString(10));
schedule.setRepeat(cursor.getString(11));
schedules.add(schedule);
}
cursor.close();
}
Log.wtf("wtf", String.valueOf(schedules.size()));
if (schedules.size() > 1) {
int i = 0;
int goodPairsCounter = 0;
while (true) {
long time1 = schedules.get(i).getTime();
long time2 = schedules.get(i + 1).getTime();
Log.wtf("TIME", String.valueOf(time1) + " - " + String.valueOf(time2));
Log.wtf("TIME", schedules.get(i).getTitle() + " - " + schedules.get(i+1).getTitle());
if (time1 > time2) {
Log.wtf("TIME", "hop");
Schedule sh = new Schedule(schedules.get(i).getId(), schedules.get(i).getColor(), schedules.get(i).getTitle(), schedules.get(i).getDesc(), schedules.get(i).getLocation(), schedules.get(i).getState(), schedules.get(i).getTime(), schedules.get(i).getTime_end(), schedules.get(i).getYear(), schedules.get(i).getRepeat(), schedules.get(i).getAccount());
schedules.remove(i);
schedules.add(i + 1, sh);
goodPairsCounter = 0;
} else {
goodPairsCounter++;
}
i++;
if (i == schedules.size() - 1) {
i = 0;
}
if (goodPairsCounter == schedules.size() - 1) break;
}
}
return schedules;
}
Here is a screenshot
Need to know how to solve this problem
CLOSED. Didn't solve it yet. If you are stuck then just find another approach
public void delete() {
String strUriCalls = "content://call_log/calls";
Uri UriCalls = Uri.parse(strUriCalls);
Cursor cc = getContext().getContentResolver().query(UriCalls, null, null, null, null);
int number = cc.getColumnIndex(CallLog.Calls.NUMBER);
int date = cc.getColumnIndex(CallLog.Calls.DATE);
if (cc.getCount() <= 0)
{
Toast.makeText(getContext(), "Call log empty", Toast.LENGTH_SHORT).show();
}
while (cc.moveToNext()) {
String callNumber = cc.getString(number);
String callDate = cc.getString(date);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
systemDate = Calendar.getInstance().getTime();
String myDate1 = sdf.format(systemDate);
//txtCurrentTime.setText(myDate);
cDate = sdf.format(Long.parseLong(callDate));
Date1 = sdf.parse(myDate1);
Date2 = sdf.parse(cDate);
//to get time diff between current date and call date
millse = Date1.getTime() - Date2.getTime();
mills = Math.abs(millse);
// to change the return value into specific time format
long hh = (mills / (1000 * 60 * 60));
Mins = (int) (mills / (1000 * 60)) % 60;
long Secs = (int) (mills / 1000) % 60;
long timeDifDays = mills / (24 * 60 * 60 * 1000);
if (timeDifDays >= 24) {
int i = getContext().getContentResolver().delete(UriCalls, callNumber, null);
if (i >= 1)
{
Toast.makeText(getContext(), "Number deleted", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(getContext(), "No such number in call logs", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
}
It deletes all the records of a particular number if one record satisfies the condition, I want to delete the satisfying record only.
public void delete() {
String strUriCalls = "content://call_log/calls";
Uri UriCalls = Uri.parse(strUriCalls);
Cursor cc = getContext().getContentResolver().query(UriCalls, null, null, null, null);
int number = cc.getColumnIndex(CallLog.Calls._ID);
int date = cc.getColumnIndex(CallLog.Calls.DATE);
if (cc.getCount() <= 0)
{
Toast.makeText(getContext(), "Call log empty", Toast.LENGTH_SHORT).show();
}
while (cc.moveToNext()) {
String callNumber = cc.getString(number);
String callDate = cc.getString(date);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
systemDate = Calendar.getInstance().getTime();
String myDate1 = sdf.format(systemDate);
//txtCurrentTime.setText(myDate);
cDate = sdf.format(Long.parseLong(callDate));
Date1 = sdf.parse(myDate1);
Date2 = sdf.parse(cDate);
//to get time diff between current date and call date
millse = Date1.getTime() - Date2.getTime();
mills = Math.abs(millse);
// to change the return value into specific time format
long hh = (mills / (1000 * 60 * 60));
Mins = (int) (mills / (1000 * 60)) % 60;
long Secs = (int) (mills / 1000) % 60;
long timeDifDays = mills / (24 * 60 * 60 * 1000);
if (timeDifDays >= 24) {
int i = getContext().getContentResolver().delete(UriCalls, BaseColumns._ID+"=?", new String[]{callNumber});
if (i >= 1)
{
Toast.makeText(getContext(), "Number deleted", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(getContext(), "No such number in call logs", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
}
I have two dates, eg. 1989-3-21, 2016-3-21 and I want to find the duration of difference between those dates. For this I am trying the following code but I am unable to get the duration of difference in dates.
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
return diff;
}
Initialize your dates like so before calling public String getTimeDiff(Date dateOne, Date dateTwo):
Date dateOne=null,dateTwo=null;
try {
dateOne = new SimpleDateFormat( "yyyy-MM-dd" ).parse("2016-3-21");
dateTwo = new SimpleDateFormat( "yyyy-MM-dd" ).parse("1989-3-21");
}
catch (ParseException ex) {
}
System.out.println( getTimeDiff(dateOne,dateTwo));
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d date(s) ", TimeUnit.MILLISECONDS.toDays(timeDiff));
return diff;
}
Since your Dates aren't in their default format you will have to use a SimpleDateFormat to explicitly declare the format of your Dates.
From here
long diff = dt2.getTime() - dt1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
Try Using This
try {
/// String CurrentDate= "10/6/2016";
/// String PrviousDate= "10/7/2015";
Date date1 = null;
Date date2 = null;
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
date1 = df.parse(CurrentDate);
date2 = df.parse(PrviousDate);
long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays);
} catch (Exception e) {
System.out.println("exception " + e);
}
Take the difference and and call the method;
long diff = dt2.getTime() - dt1.getTime();
public static String toHumanReadableTime(long diff) {
Long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60 * 60);
Long minutes = TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% (1000 * 60);
Long seconds = TimeUnit.SECONDS.convert(diff, TimeUnit.MILLISECONDS);
diff= diff% 1000;
Long milisec = diff;
StringBuilder buffer = new StringBuilder();
if (hour != null && hour > 0) {
buffer.append(hour).append(" Hour ");
}
if (minutes != null && minutes > 0) {
buffer.append(minutes).append(" Minute ");
}
buffer.append(seconds).append(" Second ");
buffer.append(milisec).append(" Millisecond ");
return buffer.toString();
}
I think there should be no difference in total time duration of play back of an audio file if we convert it between different formats.
For example if I record wave file of total time duration for 2 seconds, its size now is 20.3 MB . now i convert this wave file to mp3 file using ffmpeg latest build it becomes 1.35 mb in sizes. Now I get the time duration of the same converted MP3 file using below code.
public static String getDurationWithMp3Spi(File file)
throws UnsupportedAudioFileException, IOException, Exception {
AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
System.out.println(" File for duration MP3 " + file.getAbsolutePath());
if (fileFormat instanceof TAudioFileFormat) {
Map<?, ?> properties = ((TAudioFileFormat) fileFormat).properties();
String key = "duration";
Long microseconds = (Long) properties.get(key);
int mili = (int) (microseconds / 1000);
int sec = (mili / 1000) % 60;
int min = (mili / 1000) / 60;
String mp3Len = null;
String mins = null;
String secs = null;
if (min == 0) {
mins = "00";
}
if (min < 10) {
mins = "0" + min;
}else{
mins = "" + min;
}
if (sec == 0) {
secs = "00";
}
if (sec < 10) {
secs = "0" + sec;
}else{
secs = ""+secs;
}
mp3Len = mins + ":" + secs;
System.out.println("time = " + min + ":" + sec);
return mp3Len;
} else {
throw new UnsupportedAudioFileException();
}
}
If I see in windows media player or any other player it will show the same duration as it is for original wave but when I get from this method it is different from originals and the difference is very big.
Is there in difference in time duration of audio file if it is converted from WAVE to MP3 or vice versa?
Any help please. the above code uses MP3SPI plugin.
the above method does the conversion and get the duration.
for (Iterator<FileItem> fileIter = fileList.iterator(); fileIter
.hasNext();) {
FileItem fileItem = fileIter.next();
// write file to disk to specified path
if (!fileItem.isFormField()) {
String fileName = fileItem.getName();
System.out.println(" file Name " + fileName);
// save file to desired destination
waveFileSavePath = processFolderAppendee(waveFileSavePath,
fileName);
File waveFile = new File(waveFileSavePath);
fileItem.write(waveFile);
Thread.sleep(100);
// do conversion
String mp3FileName = fileName.replace("wav", "mp3");
mp3Path = mp3Path + "/" + mp3FileName;
convertToMP3(servletContext, waveFileSavePath, mp3Path);
Thread.sleep(100);
// prepare data(s)
GuestMessagesForm guestMessageForm = prepareGuestMessageData(
accountId, waveFileSavePath, mp3Path);
PlayListMessagesForm playListMessageForm = preparePlayListMessageData(accountId);
// save data(s)
// this method calls duration
saveGuestMessage(guestMessageForm);
savePlayListMessage(playListMessageForm);
} else {
// do nothing
}
waveFileSavePath = servletContext.getRealPath(recordDir);
}