Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I tried making an app where the user gets 20 seconds to click a button and at the end of the time the total number of clicks are recorded and displayed
The program is neither terminating nor executing

What I have tried:

private TextView t1;
private Button btn;
private int count = 0;
private long startTime = System.currentTimeMillis();
private long endTime = System.currentTimeMillis()+20000;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

t1 = (TextView)findViewById(R.id.textView);
btn = (Button)findViewById(R.id.button);

while(startTime < endTime)
{
btn.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View view)
{
count = count + 1;
}
});
}
t1.setText(Integer.toString(count));
}
Posted
Updated 14-Jun-17 12:05pm

1 solution

while (startTime < endTime)

First problem: you're comparing two fixed values, which are initialized once and then never change.

You're going to want to replace startTime with System.currentTimeMillis().

btn.setOnClickListener(new View.OnClickListener() ... 

Second problem: you're never asking the code to terminate. Instead, you're adding a new "click" handler over and over again in a tight loop.


A simple solution would be to add the handler once, and check the time limit within the onClick method:
private TextView t1;
private Button btn;
private int count = 0;
private long endTime;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    endTime = System.currentTimeMillis() + 20000;
    t1 = (TextView)findViewById(R.id.textView);
    
    btn = (Button)findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (System.currentTimeMillis() < endTime) {
                count = count + 1;
                t1.setText(Integer.toString(count));
            }
        }
    });
} 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900