Class countdown timer doesn't reset - java

I have a class countdown timer that I want to reset but when it resets it wont start again.
Basicaly when the counter gets to 0 (when the status is "done"), sets x = 1 and then in the activity checks if x = 1 , and then the counter resets. When the reset method from within the class is called it shows that it has reset but it wont start counting again
Timer class:
public class countdown_timer {
private long pls;
private long millisInFuture;
private long countDownInterval;
private boolean status;
int x = 0;
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
this.millisInFuture = pMillisInFuture;
this.countDownInterval = pCountDownInterval;
this.pls = pMillisInFuture;
status = false;
Initialize();
}
public void Stop() {
status = false;
}
public int GetNumberX() {
return x;
}
public void Reset() {
millisInFuture = pls;
x=0;
}
public void Start() {
status = true;
}
public void Initialize() {
final Handler handler = new Handler();
Log.v("status", "starting");
final Runnable counter = new Runnable() {
public void run() {
long sec = millisInFuture / 1000;
if (status) {
if (millisInFuture <= 0) {
Log.v("status", "done");
x = 1;
} else {
Log.v("status", Long.toString(sec) + " seconds remain");
millisInFuture -= countDownInterval;
handler.postDelayed(this, countDownInterval);
}
} else {
Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
handler.postDelayed(this, countDownInterval);
}
}
};
handler.postDelayed(counter, countDownInterval);
}
Activity that uses the timer class:
mycounterup = new countdown_timer(startcard, 1000);
xup = mycounterup.GetNumberX();
if (xup == 1) {
mycounterup.Reset();
mycounterup.Start();
Thanks for any help.

try changing your start method as and one thing more i don't know if its a typo or what change mycounter.Start(); to mycounterup.Start();
public void Start() {
status = true;
Initialize();
}
save the counter state so that next time if you have to pause or resume the thing you are able to do it also

You should change your Reset method:
public void Reset() {
millisInFuture = pls;
x=0;
Initialize();
}

Related

Android delay inside while loop

I have a class extending Thread. Inside this run I have a few method working in while loop. Now I want one of this methods gameSurface.updateBitmapObjects() to work with delay. How to achieve this? Here is my code:
GameThread.java:
public class GameThread<T extends GameSurface> extends Thread {
private boolean isRunning;
private long startTime, loopTime;
private long delay = 33;
private SurfaceHolder surfaceHolder;
private T gameSurface;
public GameThread(SurfaceHolder surfaceHolder, T gameSurface) {
this.surfaceHolder= surfaceHolder;
this.gameSurface = gameSurface;
isRunning = true;
}
#Override
public void run() {
while(isRunning) {
startTime = SystemClock.uptimeMillis();
Canvas canvas = surfaceHolder.lockCanvas(null);
if(canvas != null) {
synchronized (surfaceHolder) {
gameSurface.updateBitmapObjects();
gameSurface.drawMapBitmap(canvas);
((GameMainSurface)gameSurface).drawCoinAndCoins();
((GameMainSurface)gameSurface).drawFieldLines(canvas);
((GameMainSurface)gameSurface).updatePlayersLabels(canvas);
if (((GameMainSurface)gameSurface).isGameMainFragment()) {
((GameMainSurface)gameSurface).setSomeValues();
}
gameSurface.drawObjects(canvas);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
loopTime = SystemClock.uptimeMillis() - startTime;
if(loopTime < delay) {
try {
Thread.sleep(delay - loopTime);
}
catch (InterruptedException e) {
Log.e("Interupted ex", e.getMessage());
}
}
}
}
}
GameMainSurface.java:
(...)
public void updateBitmapObjects() {
this.chibi1.update();
(...)
}
MovingObject.java:
// I want this method to work with delay let's say 100 ms
public void update() {
this.colUsing++;
if (colCount == 13) {
if (colUsing >= 9) {
if (rowUsing == ROW_TOP_TO_BOTTOM_CHIBI || rowUsing == ROW_BOTTOM_TO_TOP_CHIBI)
colUsing = 1;
else
colUsing = 0;
}
}
if (colCount == 4) {
if (colUsing >= 4) {
this.colUsing = 0;
}
}
}

Stop, close, end, thread in java based on condition

I am not sure how to get this working. I want one this tread to stop once (startNumber == 0 || !Player.cCounting). !Player.cCounting is a boolean that is accessed. If either condition is met I want the loop to stop.
public class Console {
static long lastTime;
static boolean cCounting = true;
static long seconds = 0;
static long delta = 0;
static int startNumber = (int) Level.cookieTime / 1000;
Thread countDown;
public Console() {
cookieCountDown();
lastTime = System.currentTimeMillis();
}
public void cookieCountDown() {
countDown = new Thread(new Runnable() {
#Override
public void run() {
startNumber = (int) Level.cookieTime / 1000;
while (startNumber != 0) {
cCounting = Game.enter;
//System.out.println(cCounting);
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (startNumber > 0 && cCounting) {
long now = System.currentTimeMillis();
delta = now - lastTime;
if (delta >= 1000) {
delta = 0;
lastTime = System.currentTimeMillis();
System.out.println("cookie " + startNumber);// print countdown;
startNumber--;
System.out.println(Player.cCounting);
if (Player.cCounting = false) {
end();
}
}
}
}
}
});
countDown.start();
}
public void end() {
System.out.println(startNumber);
System.out.println(cCounting);
if (startNumber == 0 || !Player.cCounting) {
System.out.println("stop");
//countDown.interrupt();
//countDown.stop();
}
}
}
You just need to exit your loop. Replace your end(); method call with return;. and make startNumber and Player.cCounting volatile e.g. volatile static int startNumber

Java simultaneous execution

I am trying execute two jobs simultaneously. One of the things that I am trying to do is displaying a count up timer and the other one is moving the ball.
This is where I create the timer and also call the moveBall method
button.addChangeListener(new ChangeListener() {
int start = 0;
public void stateChanged(ChangeEvent e) {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
timeValue.setText(++start + " sec");
}
};
timer = new Timer(1000, taskPerformer);
timer.start();
ball.moveBall();
}
});
This is my moveBall method
public void moveBall() {
Thread ball = new Thread() {
double counter = 0;
int t = (int) (2 * Vy / 9.8);
public void run() {
try {
while (t >= 0) {
// calculate Vx and Vy
Ball.this.setX(Ball.this.getX() + Vx);
Ball.this.setY(Ball.this.getY() - Vy);
counter += 50;
if (counter == 1000) {
t--;
counter = 0;
}
paintingComponent.repaint();
Thread.sleep(20);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ball.start();
}
When I execute the above code the label for displaying the time passed is not changing at all during the ball is moving and when the movement is over it takes the last number that it supposed to take.
This is a example two executions of two threads, Java simultaneous execution
public class ThreadExecutor extends Thread {
private String name;
private int executionCount;
public ThreadExecutor(final String name, final int executionCount) {
this.name = name;
this.executionCount = executionCount;
}
#Override
public void run() {
int count = 1;
while (count <= executionCount) {
System.out.println("Executing thread ".concat(name).concat(" : ") + count);
count++;
}
}
}
public class Main {
public static void main(String args[]) {
final ThreadExecutor one = new ThreadExecutor("One", 1);
final ThreadExecutor two = new ThreadExecutor("Two", 2);
one.start();
two.start();
}
}

How to use Java.Util.Timer

I want to make a simple program that counts seconds up until 100 using Java.Util.Timer
The code below is the code I am using, however it simply prints all the numbers out at once without waiting a second between each one. How would I fix that? (Ordinarily I would use a thread.sleep but this is just proof of concept.)
import java.util.Timer;
import java.util.TimerTask;
public class Main {
static Timer timer = new Timer();
static int seconds = 0;
public static void main(String[] agrs) {
MyTimer();
}
public static void MyTimer() {
TimerTask task;
task = new TimerTask() {
#Override
public void run() {
while (seconds < 100) {
System.out.println("Seconds = " + seconds);
seconds++;
}
}
};
timer.schedule(task, 0, 1000);
}
}}
Don't use this while loop:
task = new TimerTask() {
#Override
public void run() {
while (seconds < 100) {
System.out.println("Seconds = " + seconds);
seconds++;
}
}
};
The while loop will run immediately as there's no delay inside of it. Instead you want to Timer itself to be your loop, meaning there's no need for this loop.
Instead use an if block to check if the count is < some max number and if so, print it out and increment the count.
task = new TimerTask() {
private final int MAX_SECONDS = 100;
#Override
public void run() {
if (seconds < MAX_SECONDS) {
System.out.println("Seconds = " + seconds);
seconds++;
} else {
// stop the timer
cancel();
}
}
};
In order to stop the timer the timer.cancel() should be invoked (not only the one of the TimerTask), so the timer is stopped and in cascade the other related threads.
#Override
public void run() {
if (seconds < Orologio.MAX_SECONDS) {
System.out.println("Seconds = " + seconds);
seconds++;
} else {
timer.cancel();
System.out.println("Timer canceled");
}
}
};

Dispatch an event to main java

I have a CountDownTimer class that when it finishes counting down it should dispatch an event to main java (or any class that uses it) letting it know it has finished.
Here is my class:
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;
public class CountTimer {
private Label targetText;
private String direction;
private int minutes;
private int seconds;
private int totalSeconds;
private int timeTotal;
private int timeLoaded;
private Boolean test;
Timer timer;
public CountTimer(int min,int sec,String dir,Label targetTextField)
{
minutes = min * 60;
seconds = sec;
timeTotal = minutes + seconds;
if (dir == "down") {
totalSeconds = minutes + seconds;
}
else {
totalSeconds = 0;
}
if (targetTextField != null) {
targetText = targetTextField;
}
direction = dir;
}
public void start()
{
timer = new Timer(){
public void run(){
timeLoaded += 1;
if (direction == "up") {
totalSeconds++;
}
else {
totalSeconds--;
}
seconds = totalSeconds % 60;
minutes = (int) Math.floor(totalSeconds / 60);
String minutesDisplay = (minutes < 10) ? "0" + Integer.toString(minutes) : Integer.toString(minutes);
String secondsDisplay= (seconds < 10) ? "0" + Integer.toString(seconds): Integer.toString(seconds);
if (targetText != null) {
targetText.setText( minutesDisplay + ":" + secondsDisplay);
}
if (test=true) {
consoleLog(minutesDisplay + ":" + secondsDisplay);
}
if(timeTotal == timeLoaded) {
//DISPATCH CUSTOM EVENT TO MAIN.JAVA HERE
Window.alert("OK");
timer.cancel();
}
}
};
timer.scheduleRepeating(1000);
}
public int getTimeTotal()
{
return timeTotal;
}
public int getTimeLoaded()
{
return timeLoaded;
}
public int getProg()
{
return (int) Math.floor(timeLoaded/timeTotal*100);
}
public native final void consoleLog(String msg)/*-{
console.log(msg);
}-*/;
}
Please help, how can i do this?
I believe you are looking to implement the Publish-Subscribe pattern.
http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
You can allow your object to have subscribers register with it. Once you have finished your operation it can then notify the subscribers that it has finished.
Example:
public interface Subscriber {
public void notify();
}
public class Publisher {
private ArrayList<Subscriber> subscribers = new ArrayList<>();
public void addSubscriber(Subscriber s) {
subscribers.add(s);
}
public void doWork() {
System.sleep(100);
notifyAll();
}
private void notifyAll() {
for(Subscriber s : subscribers) {
s.notify();
}
}
}
There are several options.
If you have this requirement frequently, or you need to notify multiple Activities/widgets, you may consider using an EventBus:
How to use the GWT EventBus
Alternatively, your CountTimer can simply call a public static method in your main class:
MyApp.doSomething();

Categories