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.
Related
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
I've got an Integer ArrayList 'timerList' (eg - 10, 20, 10) of values which I then want to use for a Countdown Timer.
I'm looking to loop through the list and restart the timer once it finishes so that it uses the next value from the list, so it counts down from 10 and then resets to 20 and then resets to 10 until all values in the list have been used.
The part i'm struggling with is looping through the values of the ArrayList. I can set the initial value from the ArrayList and I'm then trying to use the array list within the onFinish() to set the next time.
I've tried creating an int variable to keep track of where abouts I am in the list and then adding 1 to this every time, to get the next list value but once it has counted down once, it just sticks at 0
Any advice or examples of how I can implement this correctly (perhaps even looking at it from a different perspective if I'm not heading in the right direction) would be greatly appreciated!
Thanks in advance
Paul
I solved this problem by creating array of countdown timers
public class MainActivity extends AppCompatActivity {
CountDownTimer[] countDownTimers;
int Time;
TextView text;
ArrayList<Integer> timeList;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text= (TextView) findViewById(R.id.text);
timeList=new ArrayList<>();
timeList.add(10*1000);
timeList.add(20*1000);
timeList.add(30*1000);
countDownTimers=new CountDownTimer[timeList.size()];
for(int i=0;i<timeList.size();i++){
final int finalI = i;
countDownTimers[i]=new CountDownTimer(timeList.get(finalI),100) {
#Override
public void onTick(long millisUntilFinished) {
long ms = millisUntilFinished;
String texts = String.format("%02d : %02d",
TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
text.setText(texts);
}
#Override
public void onFinish() {
if(!((finalI +1)>=timeList.size())){
countDownTimers[finalI+1].start();
}
}
};
}
countDownTimers[0].start();
}
}
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);
I want to display the income of a person in a certain time. For this I ask for the income per month (=gehalt) and working hours per week (stunden) in another activity. Then in the second activity I want to increase the TextView showGehaltproSekunde (id = textViewZahl) every second by the income per second.
I am a beginner, so I don't know what exactly I have to write in public void run(). Or is there another possibility to increase the number every second?
I hope someone can help me. Thank you!
public class SecondScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondlayout);
Timer t, timer;
Intent getGehalt = getIntent();
float gehalt = getGehalt.getFloatExtra("Gehalt", 0);
Intent getStunden = getIntent();
float stunden = getStunden.getFloatExtra("Stunden", 0);
double gehaltProSekunde = gehalt/4/stunden/3600;
double gehaltProSekundeRounded = Math.round(gehaltProSekunde*1000)/1000.0;
TextView showGehaltProSekunde = (TextView)findViewById(R.id.textViewZahl);
showGehaltProSekunde.setText(gehaltProSekundeRounded+" €");
t = new Timer();
t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
}
});
}
}
For example analysis this:
private Handler mHandler = new Handler();
private boolean wasRun = true;
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if(wasRun){
//whatever you want to do if run
//you can add you want to increase variable here
}
mHandler.postDelayed(this, 1000);
}
}, 1000); // 1 seconds
Just to give some advice not strictly related to your question (#altan yuksel answered it well), i just wanted to throw my opinion in on your calculations.
You calculate the monthly salary to seconds using salary/4/hours worked in a week/3600(seconds in an hour) however not all months have exactly 4 working weeks (actually only February).
May i suggest asking for yearly salary and performing:yearly salary / 52 / hours worked in a week / 3600
Or with your current input data:(monthly salary * 12) / 52 / hours worked in a week / 3600
If you try these to your own you may find them to be a little more accurate.
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.