measuring the time is not working - java

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.

Related

Using a timer to count seconds and update a string within the activity

I'm trying to make a timer within one of my activities that will get triggered every second, increment the seconds variable and then increasing minutes by one if seconds == 60, increasing hours by one if minutes == 60.
_currentSeconds = _level.GetTimeSpentSeconds();
_currentMinutes = _level.GetTimeSpentMinutes();
_currentHours = _level.GetTimeSpentHours();
String currentTimeDisplay = _currentHours + "H " + _currentMinutes +"M " + _currentSeconds +"S";
_txtCurrentTime = findViewById(R.id.txtCurrentTime);
_txtCurrentTime.setText(currentTimeDisplay);
_totalGameTime = new Timer();
_totalGameTime.schedule(new TimerTick(), 1000);
}
private class TimerTick extends TimerTask{
TextView _txtCurrentTime = findViewById(R.id.txtCurrentTime);
public void run() {
_currentSeconds++;
TextView _txtCurrentTime = findViewById(R.id.txtCurrentTime);
if (_currentSeconds == 60){
_currentSeconds = 0;
_currentMinutes++;
}
if (_currentMinutes == 60){
_currentMinutes = 0;
_currentHours++;
}
String currentTimeDisplay = _currentHours + "H " + _currentMinutes +"M " + _currentSeconds +"S";
_txtCurrentTime.setText(currentTimeDisplay);
_level.SetTimeSpentSeconds(_currentSeconds);
_level.SetTimeSpentMinutes(_currentMinutes);
_level.SetTimeSpentHours(_currentHours);
}
}
It's hard to tell exactly how the program is responding because of how leggy my activity has gotten with the debugger attached but this doesn't seem to be doing the trick, the TextView stays the same.
For doing this, you need not use a TimerTask. You can use one of the following :
You can use this class I have written for a similar purpose - CountUpTimer
You will have to define onTick() to update your TextView every 'mCountUpInterval' time interval (defined in the CountUpInterval class)
Chronometer
Use a chronometer... Just implement the Chronometer in XML or Code and use its start() method to start it and its stop() method to stop it.
https://developer.android.com/reference/android/widget/Chronometer

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);

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++;
}
}

Time between two button clicks

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;

How can you make a stopwatch with the chronometer that shows milliseconds?

Hi I'm trying to make a scoreboard but I can't figure out how to get it to display milliseconds. In my xml a textview that displays ".000" and in my main java class I have
public class MainActivity extends Activity {
timeEx = (TextView) findViewById(R.id.timeEx);
ending= 000;
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
if (running == true){
}else{
MyChronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
MyChronometer.start();
running = true;
TimeEnd();
}
}
}
private void TimeEnd() {
// TODO Auto-generated method stub
while(running == true){
ending ++;
timeEx.setText("."+ ending );
if (ending == 999)
ending = ending - 999;
}
}
};
}
elapsedRealtime() already is in milliseconds (specifically, "milliseconds since the system was booted, including deep sleep").
If you want to display the elapsed time as seconds with a decimal point (e.g., the TextView should show "2.198"), divide the calculated time difference by 1000. If you only want the milliseconds portion (e.g., the TextView should show "198"), then use the modulo operator to get the remainder of division by 1000.

Categories