Java – Slight delay when clicking buttons

Slight delay when clicking buttons… here is a solution to the problem.

Slight delay when clicking buttons

I just made a simple app using the JodaTime library. It is nothing special, only calculates the time difference (24-hour clock) and outputs it on the screen. For example, the time difference between 21 and 03 is 6 hours. Nothing special, the app works fine.

But I have a question. When I hit the “Calculate” button, I experienced some unusual delays. Like when I click the button, it takes 3 seconds to “calculate” on the emulator. On my phone, it takes half a second. But you can see that the calculation is not instantaneous. But when I wanted to calculate a second time, it immediately had no problem. On actual phones and emulators. Can someone tell me what might be wrong? This is my onClick code (in the activity I only have a reference to the View). As far as I can tell, it should be the object issue: Loaded into memory? Because there is no delay when they are present in memory. How can I improve my code so that there are no more delays?

@Override
public void onClick(View ClickedView) {

hour1 = Integer.parseInt(field_hour1.getText().toString());
    hour2 = Integer.parseInt(field_hour2.getText().toString());

if(hour2 < hour1) {

dt1 = new DateTime(2012, 10, 10, hour1, 00);
        dt2 = new DateTime(2012, 10, 10+1, hour2, 00);
        diff = Hours.hoursBetween(dt1, dt2);

} else {
        dt1 = new DateTime(2012, 10, 10, hour1, 00);
        dt2 = new DateTime(2012, 10, 10, hour2, 00);
        diff = Hours.hoursBetween(dt1, dt2);

}

result.setText(""+diff.getHours()); }

Solution

You can try this

public static int diff(int hour1, int hour2) {
    if(hour2 < hour1) {
        hour2 += 24;
    }
    return hour2 - hour1;
}

Related Problems and Solutions