Reputation: 3152
I'm pretty new to Android's Java (so please don't beat me up) and I have a question to my button action. The called method is running only one time. When I click the button the second time nothing happens anymore. I do not understand why. No errors, no flaws, the method is doing what is expected. Any hints? Thanks!
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView mainFortuneTextView;
Button mainFortuneButton;
private int counter, i, x;
//private int randomNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 1. Access the TextView defined in layout XML
// and then set its text
mainFortuneTextView = (TextView) findViewById(R.id.fortuneTextView);
// 2. Access the Button defined in layout XML
// and listen for it here by using "this"
mainFortuneButton = (Button) findViewById(R.id.fortuneButton);
mainFortuneButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// happens on button action in main view
runThread();
Random rnd = new Random();
x = rnd.nextInt(11) + 1;
}
private void runThread() {
mainFortuneButton.setEnabled(false);
new Thread() {
public void run() {
while (i++ < 10) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
mainFortuneTextView.setText("#" + i);
}
});
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// activate button again
runOnUiThread(new Runnable() {
@Override
public void run() {
mainFortuneButton.setEnabled(true);
}
});
}
}.start();
}
}
Upvotes: 0
Views: 532
Reputation: 20500
Your variable i
used in your while is a field. That means that it will not reset. That's why the second time you call your thread the i
value will be 10 and it will be called not again. You have to reset your i
again before starting a new thread.
Upvotes: 2