I`m currently trying to obtain a CountDownTimer based on the time in milliseconds of a Calendar object. The startTimer function works, so does the timerSort function. The thing is that when the timer gets initialized with the timeLeft value, it never start from a value lower than 60 seconds. This eventually causes delays bigger than 10 seconds. any suggestions?
Thank you.
Code:
private void startTimer(String x){
counter = new CountDownTimer(timeLeft,1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
updateCountdownText();
}
#Override
public void onFinish() {
timerRunning = false;
int comp = Integer.parseInt(x);
Toast.makeText(getApplicationContext(), "Alarm received!", Toast.LENGTH_LONG).show();
cal[comp].add(Calendar.MINUTE,rec[comp]);
//Update txt file
int month = cal[comp].get(Calendar.MONTH)+1;
int day = cal[comp].get(Calendar.DAY_OF_MONTH);
String data = cal[comp].get(Calendar.HOUR_OF_DAY) + ","
+cal[comp].get(Calendar.MINUTE) + ","
+day+ "," + month + ","
+cal[comp].get(Calendar.YEAR) + "," + rec[comp] + ",";
try {
FileOutputStream stream = new FileOutputStream(file[comp], false);
try {
stream.write(data.getBytes());
}catch (Exception e){
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//end update
timerSort();
BluetoothGattCharacteristic C = btper.getCharacteristic(UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"),UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"));
//If device is disconnected => it will crash
btper.writeCharacteristic(C , x.getBytes(StandardCharsets.UTF_8), WriteType.WITH_RESPONSE);
speak(String.valueOf(comp+1));
}
}.start();
}
private void updateCountdownText() {
if(counterView.getVisibility() != View.VISIBLE)
counterView.setVisibility(View.VISIBLE);
int minutes = (int)timeLeft / 1000 / 60;
int seconds = (int)timeLeft /1000 % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"Time left until next pill: %02d:%02d",minutes,seconds);
if(timeLeftFormatted.contains("00:00"))
counterView.setVisibility(View.INVISIBLE);
counterView.setText(timeLeftFormatted);
}
private void resetTimer(){}
private void timerSort(){
Context context = getApplicationContext();
int i,j;
j = 0;
int fileindex = 0;
int hour, day, month, minute, year;
calendar = Calendar.getInstance();
timeLeft = 0;
for (i = 0; i<20; i++){
fileindex = i+1;
file[i] = new File(context.getExternalFilesDir(null).getAbsolutePath(),"pills"+fileindex+".txt");
cal[i] = (Calendar) calendar.clone();
//Read text from pills file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file[i]));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
String str = text.toString();
List<String> elephantList = Arrays.asList(str.split(","));
hour = Integer.parseInt(elephantList.get(0));
minute = Integer.parseInt(elephantList.get(1));
day = Integer.parseInt(elephantList.get(2));
month = Integer.parseInt(elephantList.get(3));
year = Integer.parseInt(elephantList.get(4));
rec[i] = Integer.parseInt(elephantList.get(5));
cal[i].set(Calendar.HOUR_OF_DAY, hour);
cal[i].set(Calendar.MINUTE, minute);
cal[i].set(Calendar.DAY_OF_MONTH, day);
cal[i].set(Calendar.MONTH-1, month);
cal[i].set(Calendar.YEAR,year);
}
// sorting:
int letsgo = 0;
Calendar tudor = Calendar.getInstance();
tudor.set(Calendar.YEAR,calendar.getMaximum(Calendar.YEAR));
for (i = 0; i<20; i++){
if(tudor.after(cal[i]) && cal[i].after(calendar)){
tudor = cal[i];
letsgo = i;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(letsgo), Toast.LENGTH_LONG).show();
TextView nextPillView = (TextView) findViewById(R.id.nextPillView);
if (!cal[letsgo].after(calendar)) {
nextPillView.setText("No Pills Scheduled");
} else {
// timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis() - Calendar.MILLISECOND;
int secleft = cal[letsgo].get(Calendar.SECOND)-calendar.get(Calendar.SECOND);
int minleft = cal[letsgo].get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);
timeLeft = secleft*1000 + minleft*60*1000 ;
//timeLeft = cal[letsgo].getTimeInMillis() - calendar.getTimeInMillis();
String theTime = String.format(Locale.getDefault(), "%02d:%02d", cal[letsgo].get(Calendar.HOUR_OF_DAY), cal[letsgo].get(Calendar.MINUTE));
month = cal[letsgo].get(Calendar.MONTH)+1;
nextPillView.setText(cal[letsgo].get(Calendar.HOUR_OF_DAY)+":"+cal[letsgo].get(Calendar.MINUTE)+ " | | Day: " + cal[letsgo].get(Calendar.DAY_OF_MONTH) + " | | Month: " + String.valueOf(month) + " | | Year: " + cal[letsgo].get(Calendar.YEAR));
startTimer(String.valueOf(letsgo));
}
}
private void speak(String x){
float pitch = 1;
float speed = 1;
mTTS.setPitch(pitch);
mTTS.setSpeechRate(speed);
mTTS.speak("It is time to administer the compartment with the lit LED",
TextToSpeech.QUEUE_ADD,null);
}
Related
I'm newly working with android Thread.
I have a thread Running:
private Thread startQuery(){
return new Thread(() -> {
Handler handler = new Handler(getApplicationContext().getMainLooper());
for(int i = 1; i <= NUMBER_OF_QUERY && isThreadAlive; i++){
int tempTime = timePerQuery;
int finalI = i;
handler.post(() -> {
Random random = new Random();
int num1 = Math.abs(random.nextInt(maxNumb1)), num2 = Math.abs(random.nextInt(maxNumb2));
setCurrentResult(num1, num2);
String strNum1 = num1 + "", strNum2 = num2 + "";
txtOp.setText(typeOfOperation);
txtNumbers.setText(equalizeNumbers(strNum1, strNum2));
queryCount = finalI;
String count = "Query No: " + queryCount;
txtQueryCount.setText(count);
});
while (tempTime > 0 && isThreadAlive){
int sec = tempTime/1000,
min = sec/60;
int sec1 = sec%60;
String s = min + " : " + sec1;
txtRemainingTime.setText(s);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tempTime -= 1000;
}
}
});
}
This thread is making values for variable "currentResult" in each iteration. Now
I want to use the value of "currentResult" from Main Thread on Clicking a button like this:
if(id == R.id.game_btnSubmit){
String strInput = edtUserResultInput.getText().toString();
if(strInput.isEmpty()){
edtUserResultInput.setError("Enter Result");
edtUserResultInput.requestFocus();
return;
}
double input = Double.parseDouble(strInput);
if(currentResult == input){
isRight[queryCount] = 1;
Toast.makeText(this, "Correct", Toast.LENGTH_LONG).show();
}
else{
isRight[queryCount] = 0;
Toast.makeText(this, "Wrong", Toast.LENGTH_LONG).show();
}
}
But the problem is, after clicking the button My app gets freeze.
Why?
Where is the problem or what is the solution?
I'm stuck with this.
Thank you <3
I want to store time slot in the arraylist. i have start time and end time. based on start time it should create time slot.
For example if start time is 09:00AM and end time is 21:00PM then it should add into arraylist like below
09:00AM
10:00AM
11:00AM
12:00PM
13:00PM
14:00PM
..... so on
21:00PM
so one user books 13:00PM to 15:00PM slots so it should not be available to another user and other slot should be available. how to compare already booking time with new array list.
Code
private void getStartHourArray() {
times = new ArrayList<TimeSlot>();
Calendar calender = Calendar.getInstance();
calender.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
int ti = calender.get(Calendar.HOUR_OF_DAY);
int minutes = calender.get(Calendar.MINUTE);
System.out.println(minutes);
String[] quarterHours = {
"00",
"30",
};
boolean isflag = false;
times = new ArrayList<>();
for (int i = 9; i < 22; i++) {
if (ti > 8) {
for (int j = 0; j < 2; j++) {
if ((i == ti && minutes < Integer.parseInt(quarterHours[j])) || (i != ti) || isflag == true) {
isflag = true;
String time = i + ":" + quarterHours[j];
if (i < 10) {
time = "0" + time;
}
String hourFormat = i + ":" + quarterHours[j];
if (i < 12) {
hourFormat = time + " AM";
} else
hourFormat = time + " PM";
TimeSlot t = new TimeSlot();
t.time = hourFormat;
t.isAvailable = "Available";
times.add(t);
}
}
}
}
if (times != null) {
load.setVisibility(View.GONE);
}
}
Time Slot model class
public class TimeSlot {
public String time;
public String isAvailable;
}
Try something like this :
String firstDate = "26/02/2019";
String firstTime = "00:00 AM";
String secondDate = "26/02/2019";
String secondTime = "12:00 PM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(firstDate + " " + firstTime);
Date dateObj2 = sdf.parse(secondDate + " " + secondTime);
System.out.println("Date Start: "+dateObj1);
System.out.println("Date End: "+dateObj2);
long dif = dateObj1.getTime();
while (dif < dateObj2.getTime()) {
Date slot = new Date(dif);
System.out.println("Hour Slot --->" + slot);
dif += 3600000;
}
This will give you a time slot for each hour, add this in ArrayList and when any user select time then remove that from ArrayList and update to the server so when next
user tries to get data it won't get the first selected user time slot.
try this:
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
public class PlayGround {
private Map<LocalTime, Boolean> slots = new HashMap();
public static void main(String[] args) {
PlayGround client = new PlayGround();
client.initializeSlots();
client.allocateSlots("10:00", "13:00");
//this shouldn't be available
client.allocateSlots("11:00", "12:00");
//not sure if u want this to be available. since it is start when the 1st just finished.
client.allocateSlots("13:00", "15:00");
client.allocateSlots("16:00", "18:00");
}
private void initializeSlots() {
LocalTime time = LocalTime.of(9, 0);
slots.put(time, true);
for (int i = 1; i < 24; i++) {
slots.put(time.plusHours(i), true);
}
}
private void allocateSlots(String strTime, String edTime) {
LocalTime startTime = LocalTime.parse(strTime);
LocalTime endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
//check if the time slots between start and end time are available
if (!slots.get(startTime) || !slots.get(endTime)) {
System.out.println("slots not available" + " start time: " + strTime + " end time: " + edTime);
return;
}
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
System.out.println("slots are available" + " start time: " + strTime + " end time: " + edTime);
//then here u can mark all slots between to unavailable.
startTime = LocalTime.parse(strTime);
endTime = LocalTime.parse(edTime);
while (startTime.isBefore(endTime)) {
slots.put(startTime, false);
slots.put(endTime, false);
startTime = startTime.plusHours(1);
endTime = endTime.minusHours(1);
}
}
}
I debugging my application then I tried clicking twice and fast on the pretty dialog button and it print twice I expect that even I clicked twice it will not print twice.
I tried error handler codes but it was not working.
prettyDialog.addButton("YES",
R.color.navy_blue,
R.color.gold_yellow,
new PrettyDialogCallback() {
#Override
public void onClick() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
raw_serial = String.valueOf(Build.SERIAL);
serial_final = raw_serial.substring(raw_serial.length() - 7);
nf = new DecimalFormat("000000");
DateFormat dateFormat = new SimpleDateFormat("MMddyyyy");
Date date = new Date();
ticket_date = dateFormat.format(date).toString();
DateFormat datetimeformat = new SimpleDateFormat("HHmmss");
Date time = new Date();
ticket_time = datetimeformat.format(time).toString();
transaction_no = serial_final + ticket_date + ticket_time + nf.format(setting_last_transaction_no);
trace_no = merchant_code + serial_final + ticket_date + ticket_time + nf.format(ref_trace_no);
print_card_no = Cardno.substring(Cardno.length() - 4);
String print_balance;
print_balance = "P" + String.valueOf(Balance);
int balancespace = 0;
int balancelength = 0;
balancelength = print_balance.length();
balancespace = 13 - balancelength;
for (int j = 0; j < balancespace; j++) {
print_balance = " " + print_balance;
}
int print = PrinterInterface.open();
Log.e("print", String.valueOf(print));
int querystatus = PrinterInterface.queryStatus();
Log.e("querystatus", String.valueOf(querystatus));
DateFormat dateformatforprint = new SimpleDateFormat("MMM.dd,yyyy");
Date dateformatprint = new Date();
String datetoprint = dateformatforprint.format(dateformatprint).toString();
DateFormat timeformattoprint = new SimpleDateFormat("HH:mm");
Date timeformat = new Date();
String timetoprint = timeformattoprint.format(timeformat).toString();
String finalStation = "";
Log.e("asdasd", "asdasd");
if (print >= 0) {
byte[] arryTitle = null;
byte[] arryTrx = null;
byte[] arrySubtitle = null;
byte[] arryBody1 = null;
byte[] arryspace1 = null;
byte[] arryFooter = null;
//test
try {
arryTitle = ("\n" + "TRIPKO" + "\n" + "\n").getBytes("UTF-8");
arryTrx = ("TRX: " + transaction_no + "\n" +
trace_no + "\n").getBytes("UTF-8");
arrySubtitle = ("Date & Time : " + datetoprint + " " + timetoprint + "\n" +
"Merchant Name: " + subcompany_name.toUpperCase() + "\n" +
"Branch : " + terminal_name.toUpperCase() + "\n" +
"-------------------------------" + "\n" +
"\n").getBytes("UTF-8");
arryBody1 = ("Card No. : " + " **** **** **** " + print_card_no + "\n" +
"Trans Type : " + " " + type_name.toUpperCase() + "\n" +
"Current Balance : " + print_balance + "\n" +
"-------------------------------" + "\n" +
"\n").getBytes("UTF-8");
arryFooter = ("Customer Service" + "\n"
+ "Hotline#: TRIPKO(678-1234)" + "\n" +
"\n").getBytes("UTF-8");
arryspace1 = "\n".getBytes("UTF-8");
} catch (Throwable e) {
e.printStackTrace();
}
begin();
if (querystatus == 1) {
writeLineBreak(20);
write(arryspace1);
alignment(1);
Fontsize(16);
boldFont(2);
doublewidth();
write(arryTitle);
backtonormal();
nextline();
Fontsize(0);
write(arryTrx);
alignment(0);
write(arrySubtitle);
write(arryBody1);
alignment(1);
write(arryFooter);
write(arryspace1);
write(arryspace1);
write(arryspace1);
write(arryspace1);
insertData(company_id,
subcompany_id,
terminal_id,
setting_control_no,
Cardno,
Balance,
transaction_no,
trace_no,
device_serial);
setting_last_transaction_no += 1;
ref_trace_no += 1;
updateTicket(String.valueOf(setting_last_transaction_no),
String.valueOf(ref_trace_no));
DBBackup();
end();
btnCheckBalance.setEnabled(true);
btnCheckBalance.setClickable(true);
Intent intent2 = new Intent(getContext(), UpdateSendingServices.class);
getActivity().startService(intent2);
} else {
//OpenNoPaper();
}
}
PrinterInterface.close();
}
});
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
totalBalance.setText("P 0.00");
btnCheckBalance.setEnabled(true);
btnCheckBalance.setClickable(true);
}
});
prettyDialog.dismiss();
}
})
.show();
I expect that it will not print twice even I clicked the "YES" pretty dialog button.
i think you can just do a trick like this
create a count variable count=0;. In button click, validate condition such that if(count==0) show dialog and make count = 1. (with this dialog will not open second time) while dismissing dialog make count = 0 again.
I think this will work
Hope it helps.
if(count == 0){
count = 1 ;
//showdialog process
}
and right before dismiss()
......
count = 0;
prettyDialog.dismiss();
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
I want to change the format of, Currently Date(YYYY-MM-DD) and Time (SS:MM:HH) to 'n' Months ago,'n' Days ago , 'n' Hours "ago" format.
CURRENT FORMAT:
REQUIRED FORMAT:
I am using Bean and Adapter class to get Current Date. Code is given Below;
Adapter Class:
public class MessageAdapter extends BaseAdapter {
private Activity activity;
private List<MessageBean> messageBeanList;
public ImageLoader imageLoader;
private Context context;
public MessageAdapter (Activity activity,List<MessageBean> messageBeanList)
{
super();
this.activity = activity;
// this.context = context;
this.messageBeanList = messageBeanList;
this.context=context;
}
#Override
public int getCount() {
return messageBeanList.size();
}
#Override
public Object getItem(int position) {
return messageBeanList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemHolder itemHolder = new ItemHolder();
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(
R.layout.message_item, null);
imageLoader=new ImageLoader(activity.getApplicationContext());
itemHolder.timestampp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(itemHolder);
} else {
itemHolder = (ItemHolder) convertView.getTag();
}
class ItemHolder
{
public TextView timestampp;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
// Your code to nofify
}
}
BEAN CLASS:
import com.google.gson.annotations.SerializedName;
public class MessageBean {
#SerializedName("date_created")
private String dateCreated = "";
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
Gone through almost every related question in SOF, but didn't get what I want as I am using bean and adapter class. Is this possible to convert Date and Time format if using JSON parsing?
I hope this will work for you..
Just add code in your adapter
/***************get current date time function*************/
String curDateTime = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
String curDateTime = df.format(c.getTime());
}catch(Exception e){}
/***************get current date time function*************/
// add simple_date_format for uniqueness
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = simpleDateFormat.parse(messageBean.getDateCreated()); // like 2016-03-09 07:08:27
Date date2 = simpleDateFormat.parse(curDateTime); // 2016-03-09 07:08:27
differentDateTime = printDifference(date1, date2);
} catch (Exception e) {
e.printStackTrace();
}
itemHolder.timestampp.setText(differentDateTime);
/************function of print different for showing date into ago format***************/
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public String printDifference(Date startDate, Date endDate){
String allDaysMonsSeconds="";
//milliseconds
long different = endDate.getTime() - startDate.getTime();
Log.d("TAG","startDate : " + startDate);
Log.d("TAG","endDate : "+ endDate);
Log.d("TAG","different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long yearInMilli = daysInMilli * 365;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
long elapsedYears = different / yearInMilli;
Log.d("TAG","%d days, %d hours, %d minutes, %d seconds %n, %d years:"+elapsedDays+","+elapsedHours+","+elapsedMinutes+","+elapsedSeconds+","+elapsedYears);
// code for showing before days...
if(elapsedDays<=0){
if (elapsedHours<=0)
{
if (elapsedMinutes<=0)
{
allDaysMonsSeconds = elapsedSeconds+" second ago";
}
else
{
allDaysMonsSeconds = elapsedMinutes+" minute ago";
}
}
else
{
allDaysMonsSeconds = elapsedHours+" hour ago";
}
}
else{
allDaysMonsSeconds = elapsedDays+" day ago";
}
return allDaysMonsSeconds;
}
/************function of print different for showing date into ago format***************/
try this,
initialize your textview first.
TextView t = new TextView();
Call below method as,
getTimeDifference(date, t);
private void getTimeDifference(String pDate, TextView time) {
int diffInDays = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar c = Calendar.getInstance();
String formattedDate = format.format(c.getTime());
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(formattedDate);
d2 = format.parse(pDate);
long diff = d1.getTime() - d2.getTime();
diffInDays = (int) (diff / (1000 * 60 * 60 * 24));
if (diffInDays > 0) {
if (diffInDays == 1) {
time.setText(diffInDays + " day ago");
} else {
time.setText(diffInDays + " days ago");
}
} else {
int diffHours = (int) (diff / (60 * 60 * 1000));
if (diffHours > 0) {
if (diffHours == 1) {
time.setText(diffHours + " hr ago");
} else {
time.setText(diffHours + " hrs ago");
}
} else {
int diffMinutes = (int) ((diff / (60 * 1000) % 60));
if (diffMinutes == 1) {
time.setText(diffMinutes + " min ago");
} else {
time.setText(diffMinutes + " mins ago");
}
}
}
} catch (ParseException e) {
// System.out.println("Err: " + e);
e.printStackTrace();
}
}
Use the following code and just concatenate ago as a string in the time:
startTime = "2016-03-09 16:23:30";
StringTokenizer tk = new StringTokenizer(startTime);
String date = tk.nextToken();
String time = tk.nextToken();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat sdfs = new SimpleDateFormat("hh:mm a");
Date dt;
try {
dt = sdf.parse(time);
System.out.println("Time Display: " + sdfs.format(dt)+" ago"); // <-- I got result here
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String curDateTime = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
String curDateTime = df.format(c.getTime());
}catch(Exception e){}
/***************get current date time function*************/
// add simple_date_format for uniqueness
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = simpleDateFormat.parse(messageBean.getDateCreated()); // like 2016-03-09 07:08:27
Date date2 = simpleDateFormat.parse(curDateTime); // 2016-03-09 07:08:27
differentDateTime = printDifference(date1, date2);
} catch (Exception e) {
e.printStackTrace();
}
itemHolder.timestampp.setText(differentDateTime);
/************function of print different for showing date into ago format***************/
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public String printDifference(Date startDate, Date endDate){
String allDaysMonsSeconds="";
//milliseconds
long different = endDate.getTime() - startDate.getTime();
Log.d("TAG","startDate : " + startDate);
Log.d("TAG","endDate : "+ endDate);
Log.d("TAG","different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long yearInMilli = daysInMilli * 365;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
long elapsedYears = different / yearInMilli;
Log.d("TAG","%d days, %d hours, %d minutes, %d seconds %n, %d years:"+elapsedDays+","+elapsedHours+","+elapsedMinutes+","+elapsedSeconds+","+elapsedYears);
// code for showing before days...
if(elapsedDays<=0){
if (elapsedHours<=0)
{
if (elapsedMinutes<=0)
{
allDaysMonsSeconds = elapsedSeconds+" second ago";
}
else
{
allDaysMonsSeconds = elapsedMinutes+" minute ago";
}
}
else
{
allDaysMonsSeconds = elapsedHours+" hour ago";
}
}
else{
allDaysMonsSeconds = elapsedDays+" day ago";
}
return allDaysMonsSeconds;
}