How To Change Background Resource of Button after Several Seconds - android

I am creating an app which is like a memory game. A button has an image resource from a drawable and I want to the background resource of a button to go back to its default background, say after 5 seconds.
Here is my code.
Collections.shuffle(ShapesArray);
this.myImg1=ShapesArray.get(0);
img1.setBackgroundResource(myImg1);
task = new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
img1.setBackgroundResource(android.R.drawable.btn_default);
}
};
Timer appear = new Timer();
appear.schedule(task, 5000);
img1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
img1.setBackgroundResource(myImg1);
String txt = PName.getText().toString();
if(txt.equals("Heart")){
if(myImg1 == R.drawable.heart){
correct++;
img1.setBackgroundResource(android.R.drawable.btn_default);
}
}
However, after the 5 Seconds, the Activity force closes and goes back to previous activity. I'm kinda new to Android. Please help. :(

You can use either handler with post delay or can use count down timer ,here i am giving an example of count down and that is-
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//This is when you click on each tick it came here after 1000 millisecond
}
public void onFinish() {
// After the time is experied so here can change image
Printer.setBackgroundResource(R.drawable.prntr);
}
}.start();
Thanks

Related

Calling on click on button when timer ends

I'm creating a quiz app in android. I have written OnClickListener for next button to load next question. now I want to add timer to each question so that when timer ends it will automatically call OnClickListener of next button. How to implement this?
If you want to delay some code from running for a certain amount of time use a Runnable and a Handler like this
Runnable r = new Runnable() {
#Override
public void run(){
doSomething(); //<-- put your code in here.
}
};
Handler h = new Handler();
h.postDelayed(r, 1000);
You just need to call performClick() on an instance of your next button. Something like this:
nextButton.performClick()
That will execute everything you have inside of OnClickListener that is set for that button.
EDIT:
If I misunderstood your question and you are searching for Timer implementation, I recommend for you check CountDownTimer that is provided by Android team. You can check documentation with an example for his here:
https://developer.android.com/reference/android/os/CountDownTimer
You can have a method you call when the user clicks the next button say it's named as nextQuestion()
then add the listener of your next button
Button nextBtn = findViewById(..);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextQuestion();
}
});
And the time would be CountDownTimer of say 1 min duration (60*1000 msec) and 1 second tick (1000 msec)
new CountDownTimer(60000, 1000) { // 1 min duration (60*1000 msec) and 1 second tick (1000 msec)
#Override
public void onTick(long millisUntilFinished) {
// do something each second
}
#Override
public void onFinish() {
// timer expired
nextQuestion();
}
}.start();

Sum Of Total Time Taken Of Timer

I am making a game.
Lets say that it has 2 levels.
I have a TIMER in both which works properly. The code for timer:
public Timer t;
public int TimeCounter = 0;
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
TextView t = (TextView)findViewById(R.id.txtcount);
t.setText(String.valueOf(TimeCounter));
TimeCounter++;
}
});
}
}, 1000, 1000);
Now in my 3rd activity i want the total time (Adding the first activity's and second activity's time taken) to be shown.
Also, I want to save the time the user took as the high score. And then when the user takes less time than the highest score, the previous will get deleted and the new will be saved
I would appreciate your help.Thanks
Make TimeCounter static
public static int TimeCounter = 0;
Now you can increment it in both of your activities like (in second activity it will retain values from first activity)
ActivityOne.TimeCounter++;
Wherever you want to get its value you can get it easily.

Simultaneous, linked threads in android

I'm working on a math game which presents the player with a simple math problem of the sort 4 + 3 = ? or 6 / 2 = ?. The player is offered 4 possible answers and clicks one. The screen has two buttons, one with an arrow, and one with a square.
The player selects the answer they think is correct. If the answer is correct they get a message. If the answer is incorrect, that choice is grayed out, and they can keep choosing until they get it right.
I want two modes of play: practice and timed.
In practice mode, the player clicks the arrow button and gets a new question. This works fine.
I also want a timed play mode. When the player presses the arrow button, a timer starts and the first problem comes up. If they get it right, they are immediately asked a new question. Again, if they are incorrect, they keep asking until they get it right. Meanwhile, there should be a timer counting down. Play stops when the timer ends or the player presses the square button.
I don't know how to do the timed play where there are two simultaneous activities: playing the game, and the timer.
I'm including pseudo-code instead of code -- the code is long. But if necessary, I can post the entire code.
Update:
This was my naive attempt. The problem is that I can't figure out how to wait in the while loop for until the player to ask the question before askQuestion() is called again. Perhaps it needs to be in a separate thread and have the while loop wait for that thread to return. Would the timer keep going? I want the timer to run simultaneously to a separate task in which a question is posed --> Player answers the question --> a new question is posed .....
public void playTimed()
{
// Toast.makeText(getApplicationContext(), "in playPractice", Toast.LENGTH_SHORT).show();
go_button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
go_button.setEnabled(false);
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished)
{
timer.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish()
{
timer.setText("done!");
go_button.setEnabled(true);
timer_done = true;
}
}.start();
while(!timer_done)
{
askQuestion();
}
}
});
}
onCreate()
{
-For all four answer buttons:
answer_button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
correct = checkAnswer(answer_button_id);
}
});
-get intent extras to know which game
-swith-case to play selected game
}
checkAnswer()
{
if (correct)
{
// feedback
handleRightAnswer();
}
else
{
// feedback
handleWrongAnswer();
}
}
askQuestion()
{
-choose type of problem (+,-,*,/)
-generate arguments and answer
-create random answer list
where one choice is correct
-display problem
-display answer choices
}
playTimed()
{
-When player presses go_button,
timer starts and first question
appears. When correct answer is
selected a new question immediately
appears. Continues until timer runs
out or player presses stop_button.
Seconds left is displayed during play.
}
playPractice()
{
//When player presses go_button
// a new question appears.
go_button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
askQuestion();
}
});
}
As Gabe Sechan stated, you can do this using a timer to update a counter, then when the counter hits 0, do something. You can also use the timer to update a TextView (to display the time remaining).
Here is a class that I have used in the past, originally found here:
public class UIUpdater{
private Handler mHandler = new Handler(Looper.getMainLooper());
private Runnable mStatusChecker;
private int UPDATE_INTERVAL = 1000; //updates every second
public UIUpdater(final Runnable uiUpdater) {
mStatusChecker = new Runnable() {
#Override
public void run() {
// Run the passed runnable
uiUpdater.run();
// Re-run it after the update interval
mHandler.postDelayed(this, UPDATE_INTERVAL);
}
};
}
public UIUpdater(Runnable uiUpdater, int interval){
this(uiUpdater);
UPDATE_INTERVAL = interval;
}
public synchronized void startUpdates(){
mStatusChecker.run();
}
public synchronized void stopUpdates(){
mHandler.removeCallbacks(mStatusChecker);
}
}
Then, in your method where you want to update your counter, you would put:
UIUpdater mUIUpdater = new UIUpdater(new Runnable() {
#Override
public void run() {
//method to update counter
}
});
//to start the method:
mUIUpdater.startUpdates();
//to stop the method, ie, when counter == 0
mUIUpdater.stopUpdates();

Why does my countdown timer in my app not stop?

I have a countdown timer which runs as soon as the generate expression button is clicked. Inside the timer I have made it work so when the timer runs it automatically clicks the button , so that the next expression is displayed. When the button is clicked 10 times it should start a new activity. But the problem I'm having is when the new activity has started it keeps starting the same activity. So i wanted the timer to stop as soon as the button has been clicked 10 times. I have tried countDownTimer.cancel(); to stop the timer as soon as 10 clicks have been clicked, but it doesn't seem to work.
Here is where the timer code is add:
public void generate_Clicked(View v){ // When Generate button is clicked
if(gencount <10){
if (!timerHasStarted) {
countDownTimer.start();
timeText.setText(timeText.getText() + String.valueOf(startTime/1000));
timerHasStarted = true;
}
else {
countDownTimer.cancel();
timerHasStarted = false;
}
// Fetch your random question
String Rquestion = multiArray[ar.get(gencount)][0];
displayExpression.setText(Rquestion);
displayAnswer.setText("");
setAnswer.setText("?");
setHints.setText("");
count =0;
gencount++;
}else{
// countDownTimer.cancel(); //This doesn't seem to work
Intent i = new Intent(getApplicationContext(),Score.class);
startActivity(i);
ar.clear();
}
} //End of generate_Clicked.
Heres the timer code:
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timeText.setText("Time's up!");
Button buttonGenerate = (Button) findViewById(R.id.random_gen);
buttonGenerate.performClick();
countDownTimer.cancel();
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished) {
timeText.setText("" + millisUntilFinished/1000);
}
}
There seems to be a bug in the CountDownTimer code, that prevents it from stopping. The cancel method does not work.
If you google you will see plenty of people describing the same problem.
So if you only start the activity when the counter is exactly 10.
if (gencount==10) {
// countDownTimer.cancel(); //This doesn't seem to work
Intent i = new Intent(getApplicationContext(),Score.class);
startActivity(i);
ar.clear();
}
instead of } else { it should work. and reset gencount when the button is clicked, and also you need to have a different way of executing the whole handling code.

A timer which auto-click this button every 20seconds

I have this button which i want to set a timer to it so that the user do not have to click it everytime, such that it auto click this button every 20seconds. How do i set it?
Basically i am using a tabhost activity, so there're total of 3 tabs. In the first tab, there is this button which i need to click the button therefore i then able to retrieve informations from webservice and this webservice will update every time. When i click on other tabs and back to the first tab, i want it to be auto refresh.. Instead of clicking the button to refresh.
holder.btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
A more efficient way IMO is using ScheduledExecutorService:
private void doTheActualJobWhenButtonClicked() {
// put whatever you need to do when button clicked here
... ...
}
... ...
holder.btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// job triggered by user click button:
doTheActualJobWhenButtonClicked();
}
});
... ...
ScheduledExecutorService scheduleTaskExecutor= Executors.newScheduledThreadPool(1);
// This schedule a task to run every 20 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// job triggered automatically every 20 seconds:
doTheActualJobWhenButtonClicked();
}
}, 0, 20, TimeUnit.SECONDS);
UPDATE:
If your button click perform some UI update for example refresh text in a TextView, then simply wrap
your method call within runOnUiThread():
private void doTheActualJobWhenButtonClicked() {
myTextView.setText("refreshed");
}
ScheduledExecutorService scheduleTaskExecutor= Executors.newScheduledThreadPool(1);
// This schedule a task to run every 20 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// involved your call in UI thread:
runOnUiThread(new Runnable() {
public void run() {
doTheActualJobWhenButtonClicked();
}
});
}
}, 0, 20, TimeUnit.SECONDS);
Also you need shutdown ScheduledExecutorService properly before open next Activity or close your current Activity:
// Shut down scheduled task before starting next activity
if (scheduleTaskExecutor != null)
scheduleTaskExecutor.shutdownNow();
Intent intent = new Intent(getBaseContext(), NextActivity.class);
startActivity(intent);
... ...
public void onDestroy() {
super.onDestroy();
// Shut down scheduled task when closing current activity
if (scheduleTaskExecutor != null)
scheduleTaskExecutor.shutdownNow();
}
Hope this help.
Since you have a button, I assume that you have an ActionPerformed-type method at someplace.
Given that, you can do this:
public class AutoClick extends Thread {
// Time to wait in milliseconds
private long wait;
//Latency excepted
private long lat;
AutoClick(long time, long latency) {
wait = time;
lat = latency;
}
public void run() {
long start = System.getCurrentTimeMillis();
long current;
while(true)
current = System.getCurrentTimeMillis();
long step = (current-start) % 20000;
if(step <= latency || step >= wait-latency)
//call the action-performed method
}
}
Then create an instance of the thread and run it:
public AutoClick clicker = new AutoClick(20000);
clicker.run();

Categories

Resources