Reputation: 403
In one click i added:
tStart = System.currentTimeMillis();
In the second click button event i added:
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;
timerValue.setText("00:00:" + tDelta);
tStart is global long var.
And timerValue is a TextView also global.
The problem is that i'm getting on the seconds of timerValue when doing setText some very long number for example: 1442257716372 and i clicked on the second button after a second or two.
Another problem is that if the time between the clicks is more then 60 seconds how do i update the minutes ?
The Runnable i'm calculating in:
Runnable serverChecksRunnable = new Runnable()
{
@Override
public void run()
{
if (connectedSuccess == true)
{
checkServer = Get(iptouse + "uploadstatus");
}
Handler h=new Handler(Looper.getMainLooper());
h.post(new Runnable()
{
@Override
public void run()
{
if (connectedSuccess)
{
if (checkServer != null)
{
long tStart;
String a = null;
try
{
a = new String(checkServer, "UTF-8");
textforthespeacch = a;
if (textforthespeacch.contains("upload completed"))
{
String varr = textforthespeacch.substring(17);
String varr1 = textforthespeacch.substring(0, 16);
textforthespeacch = varr1;
status1.setText("Upload completed" + " " + varr + "%");
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;
timerValue.setText("00:00:" + elapsedSeconds);
numberofuploadedfilescounter += 1;
uploadedfilescount.setText(("Uploaded Files: " + numberofuploadedfilescounter));
MainActivity.this.initTTS();
}
if (textforthespeacch.contains("uploading"))
{
String[] split = textforthespeacch.split(" ");
textforthespeacch = split[0];
status1.setText("Uploading" + " " + split[1] + "%");
tStart = System.currentTimeMillis();
servercheckCounter += 1;
if (servercheckCounter == 1)
{
MainActivity.this.initTTS();
}
}
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
}
});
customHandler.postDelayed(serverChecksRunnable,1000);
}
};
What should i init tStart to ? I did first time long tStart = 0;
Now i removed the 0 but then i'm getting error on the tStart later in the code say that the variable is not initialized.
The reason i moved the tStart to the top of the Runnable is that the tStart is not in the same place of the tDelta and the tEnd.
Upvotes: 0
Views: 220
Reputation: 66999
Using the answer by @bobince to this other question, you can do this:
long s = (System.currentTimeMillis() - tStart) / 1000;
timerValue.setText(String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60)));
Upvotes: 1
Reputation: 1676
For better formatting, you can use:
double secs = (tDelta /1000.0) % 60;
int mins = (int)Math.floor(tDelta /(1000*60));
String text = String.format("00:%02d:%06.3f", mins, secs);
Upvotes: 1