Time between two button clicks - java

I´ve two buttons and I want to count the time between two clicks. I know how to do that once:
Long starttime = System.currentTimeMillis();
Long endtime = System.currentTimeMillis();
Long differenz = ((endtime-starttime) / 1000);
Now, I want on the second click, that the count starts from zero again until the first button is clicked. Then, measure the time between first and second button click and so on.
Maybe it´s a really simple thing but I don´t know how to do...
EDIT: Ok, I try to make it clear:
I have Button A and B. I want the user to alternately push button A and B. When the user clicks on Button A, I want a timer to measure the time until B is clicked. Until here, everything is clear to me.
Now I want that the time between the click on B till the click to A is measured, always alternated between A and B.
I don´t know what to do after the click on B that the time is measured again until A.

Class members
boolean mButtonAClicked;
boolean mButtonBClicked;
long mStartTime = 0;
When Button A is clicked
if (mButtonAClicked)
{
// button A is clicked again, stop application
}
else
{
mButtonAClicked = true;
mButtonBClicked = false;
if (mStartTime != 0) // Button B was clicked
{
Long endtime = System.currentTimeMillis();
Long differenz = ((endtime-starttime) / 1000);
mStartTime = System.currentTimeMillis();
}
}
When Button B is cliked
if (mButtonBClicked)
{
// button B is clicked again, stop application
}
else
{
mButtonBClicked = true;
mButtonAClicked = false;
if (mStartTime != 0) // Button A was clicked
{
Long endtime = System.currentTimeMillis();
Long differenz = ((endtime-starttime) / 1000);
mStartTime = System.currentTimeMillis();
}
}

Create a field to hold last time each was pressed.
long aMillisPressed;
long bMillisPressed;
When Button A is clicked:
aMillisPressed = System.currentTimeMillis();
long timeElapsedSinceBPressed = aMillisPressed - bMillisPressed;
And when B is clicked:
bMillisPressed = System.currentTimeMillis();
long timeElapsedSinceAPressed = bMillisPressed - aMillisPressed;

Related

Detect for how long if and else statements were executed

In processing (which is based on java), the draw method is constantly being executed as long as the program is running. I'm trying to measure for how long the condition in the if statement was true.
I have a if statement:
if (matrix [3][5]== 3) {
System.out.println("Closed");
}
else {
System.out.println("Opened");
}
The value of matrix [3][5]changes dynamically (I use Reactivision, and based on some markers position, this value will change). When I run the program, the condition is false so I'll have:
opened
opened
...
opened
and then the condition will be true so it will print:
closed
closed
etc
Before eventually turning back to opened.
I want to measure for how long the condition was true and printed closed, and when it changes, for how long it stayed opened etc: for each lapse of time it returned opened or closed, I want to know for how long.
I started a timer in my setup:
void setup () {
startTime = System.nanoTime();
}
that I could end in the if statement:
if (matrix [3][5]== 3) {
System.out.println("Closed");
long estimatedTime = System.nanoTime() - startTime;
System.out.println("Was opened for"+ estimatedTime);
}
So I would know for how long it's been opened. But how can I make it start again to make it measure now for how long it's closed, then opened etc back and forth ?
I can't figure this out
You can set a new start time in the else branch. And you should set an extra flag indication the last state.
if (matrix [3][5]== 3) {
System.out.println("Closed");
if (isOpen)
{
isOpen=false;
System.out.println("Runtime: " + (System.nanoTime() - startTime));
}
}
else {
if (!isOpen)
{
startTime=System.nanoTime();
isOpen = true;
System.out.println("Opened");
}
}
Something this way. The result depends on the switch frequency. "System.nanoTime()" may return the same time for different calls.
You're on the right track. You can use the nanoTime() or millis() functions to record the start time, and then simply use that same function to record the current time. Subtract the start time from the current time to get your elapsed time.
Here's an example that keeps track of how much time has elapsed since the user clicked:
int start;
void setup(){
size(200, 100);
start = millis();
}
void draw(){
background(0);
int now = millis();
int elapsed = now - start;
text("Elapsed: " + elapsed, 25, 25);
}
void mouseClicked(){
start = millis();
}
Try to repeat your setup() logic in else:
boolean flag = true;// opened is true.
if (matrix[3][5] == 3) {
if (flag) {
long estimatedTime = System.nanoTime() - startTime;
System.out.println("Was opened for" + estimatedTime);
startTime = System.nanoTime();
flag = false;
}
System.out.println("Closed");// or place in the nested if to be less verbose.
} else {
if (!flag) {
long estimatedTime = System.nanoTime() - startTime;
System.out.println("Was closed for" + estimatedTime);
startTime = System.nanoTime();
flag = true;
}
System.out.println("Opened");
}
GL!
You can keep 2 fields in class, where you want to measure a time of opened status as below:
private Long startOpenedStatus=null;
private Long endOpenedStatus=null;
private int[][] matrix=new int[5][5];
public void yourMethod(){
//...
if (matrix [3][5]== 3) {
stopMeasure();
System.out.println("Closed");
}
else {
startMeasure();
System.out.println("Opened");
}
//...
}
/** take time of start opened status, takes only one (first time method fire) in opened session */
private void startMeasure(){
if(startOpenedStatus==null){
//reset time of end the opened status
endOpenedStatus=null;
startOpenedStatus=new GregorianCalendar().getTimeInMillis();//returns actual time in miliseconds for start of opened status
}
}
/** take time of end opened status, takes only one time in closed session*/
private void stopMeasure(){
if(endOpenedStatus==null){
endOpenedStatus=new GregorianCalendar().getTimeInMillis();//returns actual time in miliseconds for end of opened Status
long timeInMilis=endOpenedStatus-startOpenedStatus; //this is interwal between end and start of time (in miliseconds)
System.out.println("opened status was for "+ timeInMilis+" in miliseconds");
System.out.println("opened status was for "+reaclculateToSeconds(timeInMilis)+" in seconds");
startOpenedStatus=null;
}
}
private BigDecimal reaclculateToSeconds(long timeInMiliseconds){
BigDecimal timeInSeconds=new BigDecimal(timeInMiliseconds).divide(new BigDecimal(1000), MathContext.DECIMAL128);
return timeInSeconds.round(new MathContext(3));
}
I think your best bet would be to keep track of the current "state" (open/closed) and reset your startTime when the "state" changes. I haven't tried the following but hopefully it starts you off in the right direction.
First you'd have to define a "lastState" String variable (probably same place you define "startTime" and initialize it in your setup. If you know the initial state, set it to that. I just used "NotSet" as an example.
void setup () {
startTime = System.nanoTime();
lastState = "NotSet";
}
Then you would need a method that compare the current state to the last state and output the elapsed time if there is a state change.
private static void logElapsed (String currentState) {
if(!lastState.Equals(currentState)) {
// state has changed so output the elapsed time and set the lastState to the currentState
long estimatedTime = System.nanoTime() - startTime;
// reset the startTime to keep track of the elapsed time of the new state
startTime = System.nanoTime();
// Output how long the last state
System.out.println("Was " + lastState + " for "+ estimatedTime);
// reset the lastState to the current state
lastState = currentState;
}
}
Finally, you would just need to call it from within your if/else block.
if (matrix [3][5]== 3) {
System.out.println("Closed");
logElapsed("Closed");
}
else {
System.out.println("Opened");
logElapsed("Opened");
}

Updating a number in a TextView every second

I'm writing my first app in which I need to update the number in a text view every second until a button is pressed. Using a handler seems to be impossible because the number is created and stored outside of the handler, but it can't be declared final because it needs to change. Thread.sleepalso seems to make the app hang indefinitely, before some code is executed that is written above it.
final TextView countView = (TextView) findViewById(R.id.counter);
countView.setText("100,000,000,000");
//set a Calendar object to be 00:00:00:00 on Jan 1, 2015
final Calendar startTime = Calendar.getInstance();
startTime.set(2015, 0, 0, 12, 0, 0);
startTime.set(Calendar.MILLISECOND, 0);
final Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//set a Calendar to be the time that the button is clicked and find the difference in ms between it and startTime
Calendar nowTime = Calendar.getInstance();
double milStart = startTime.getTimeInMillis();
double milNow = nowTime.getTimeInMillis();
double diff = (milNow-milStart)/1000; //difference in seconds between "start" date and current date
double total = 100000000000L; //# that needs to be updated
for(long i = 0L; i < diff; i++) {
total += 1.8;
}
countView.setText(NumberFormat.getInstance().format(total));
I need to continue to increment total by 1.8 every second or by 1 every 556 milliseconds.
while(true) {
countView.setText(NumberFormat.getInstance().format(total));
total += 1.8;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
Causes the app to hang indefinitely as soon as the button is clicked, so that even the first countView.setText(NumberFormat.getInstance().format(total)); doesn't execute.
Using a handler doesn't seem possible to me since total can't work if declared final, but creating a variable inside the handler and looping it would cause the value to never change.
Am I missing an obvious solution? This is my first real endeavor with Java so it's all new to me
you may use Handler
Handler h = new Handler();
final Runnable r = new Runnable() {
int count = 0;
#Override
public void run() {
count++;
textView.setText(""+count*1.8);
h.postDelayed(this, 1000); //ms
}
};
h.postDelayed(r, 1000); // one second in ms
for stopping you may use h.removeCallbacksAndMessages(null);

measuring the time is not working

I want to measure the time between the 1st button click and the 3rd button click. I'm not getting any sort of thext on the main screen, where the textView1 is placed. If i'm launching the app, I'm getting a nullpointer. What does thar mean?
#Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt(800);
int y = r.nextInt(800);
long startTime = SystemClock.elapsedRealtime();
i++;
View b = findViewById(R.id.start_time);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
Well, that function isn't doing what you think. startTime is a local variable and will be cleared every time the function exits. If you want to keep the time between button presses, you need to use a class variable. You would also not want to initialize startTime unless i==1. Right now you're doing it each time and that will cause it to always have a 0 (or very close to 0) difference.
Also why are you using an intent for the toast? At best that's a waste, at worst its a problem. There's no reason for it. Just convert the difference to a string.

Find duration between touch events in android

I have set up an onTouchListener which allows the user to click textView2 exactly 10 times, as shown below. My goal is to measure the time between touch 1 and touch 2, and store it as a variable, say time1. However, I'm not quite sure how to do this. One idea I had was setting up a variable, i, that measures the number of times the TouchListener was clicked. I was thinking of potentially measuring the time that i contained a particular value (for example, if i was equal to 1 for 1 second, this means the time between touch 1 and touch 2 was 1 second). However I'm not sure how to implement this, and I'm not even sure if this is the correct method. Does anyone know how to solve this problem?
.java file
public class MainActivity extends Activity {
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView2 = (TextView)findViewById(R.id.textView2);
i=0;
textView2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
i++;
if (i==10) textView2.setOnTouchListener(null);
}
return false;
}
});
}
In your class
private long pressTime = -1l;
private long releaseTime = 1l;
private long duration = -1l;
Then in your onTouch method
if(event.getAction() == MotionEvent.ACTION_DOWN){
pressTime = System.currentTimeMillis();
if(releaseTime != -1l) duration = pressTime - releaseTime;
}
else if(event.getAction() == MotionEvent.ACTION_UP){
releaseTime = System.currentTimeMillis();
duration = System.currentTimeMillis() - pressTime;
}
Now you have your duration between touch events:
Duration when you press down is the time between the last time you released and the current press (if you have previously pressed down and released the button).
Duration when you release is the time between the last time you pressed down and the current release time.
-Edit-
If you need to know the difference in time of all events you can just do something like
private long lastEvent = -1l;
private long duration = -1l;
Then in onTouch event
if(lastEvent != -1l) duration = System.currentTimeMillis() - lastEvent;
lastEvent = System.currentTimeMillis();
You can also create a list of durations
private List<Long> durations = new ArrayList<Long>();
and in onTouch instead of duration = ... do
durations.add(System.currentTimeMillis() - lastEvent);
This could be useful for checking all durations between all sequential events. For example, if you want to know the time between pressing down, dragging, stopping dragging, starting dragging, and then lifting up you could check your list after you lift up for every time in question instead of having to constantly check a single duration.
You may want to keep a record of events in a List. The objects stored in this list would keep the timestamp of the touch event, and since UI events are dispatched by a single thread and the clock is monothonic, you are guaranteed that event at N + 1 has a later (at most equal) timestamp than event at index N.
I'm not sure about how you clean this list, however. It depends on how and why you read events, which in turn depends on what you want to do with the delay between two subsequent touch.
For example, if you just wanted to display the time since last touch, a simple code like this could be enough:
public class MyActivity {
private int times = 0;
private long lastTimestamp;
private void onTouchEvent(Event evt) {
if (times > 0) {
long delay = evt.getTimestamp() - lastTimestamp;
// do something with the delay
}
lastTimestamp = evt.getTimestamp();
times++;
}
}

Using time to determine what instruction is carried out - android

Is there a way to use a timestamp or other feature to determine what action is carried out?
e.g. when a button is clicked 'A' is performed unless the button has been clicked within the last second, otherwise perform B
You can use System.currentTimeMillis(), it returs time in millisecond,
e.g.
long last_click = 0;
// this is you interval time in milliseconds
long myTimeMillis = 1000;
// ... ... ...
// inside button click function
long time = System.currentTimeMillis()
if(time-last_click > myTimeMillis){
do_taskA();
}else{
do_taskB();
}
last_click = time;

Categories