Sriram Sriram - 3 months ago 30
Java Question

Disable Button on CardView android

I am having trouble in setting the

Button
to invisible on a
CardView
after particular time

What i am trying to achieve:
I have a
CardView
with a
Button
.
When user places an order, order date & time is stored in MySQL server DB. I get this time from server and add 10 mins delay to it.

Now this time is considered to make the
Button
invisble/gone in
CardView
.

What am i using:
For time, am using Joda Time &
whatever code below is inside the
onBindViewHolder()
of
Recyclerview


What i have tried so far:
I get the time from server

String orderDate = cOrder.getOrderDate(); // 2016-08-18 00:02:32


Then convert the time to
Date
format

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt = dateTimeFormatter.parseDateTime(orderDate);


I add 10 minutes to the time using the below, to set the delay

DateTime delay = dt.plusMinutes(10);


Now i set the delay time on the
Button
using
postDelayed()


holder.btnCancel.postDelayed(new Runnable() {
@Override
public void run() {
holder.btnCancel.setVisibility(View.GONE);
}
}, delay.getMillis());


Now when i run the app, the button on the
CardView
should have disappeared as orderDate was (18th Aug - Two days before current).

I tried using regular Java time as well instead of JODA but no luck.

I am unable to figure out what the issue is. Requesting your guidance.

Thanks

Answer

From the documentation of postDelayed():

delayMillis long: The delay (in milliseconds) until the Runnable will be executed.

Let's add 10 minutes to 2016-08-18 00:02:32 and convert it to milliseconds (from the epoch). That equals to something like 1471471952000.

You're passing this value to postDelayed() as the delay, effectively telling the Handler to execute this Runnable after 1471471952000 milliseconds, which is roughly equals to 47 years.

That does not really make sense.

To hide your Button if the given Date is before the current Date, you could do something like this:

String orderDateString = cOrder.getOrderDate();
try {
    Date now = new Date();
    Date orderDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
            Locale.getDefault()).parse(orderDateString);

    if(orderDate.before(now)) {
        holder.btnCancel.setVisibility(View.GONE);
    }
} catch (ParseException pe) {
    pe.printStackTrace();
}
Comments