M.A.Murali
M.A.Murali

Reputation: 10148

problem in thread running

i doing simple stop watch with [start/pause] and [reset] button. problem occur when i pressed start button after pause. the run method is not calling. please help me. my code is

public class StopWatch3 extends Activity implements Runnable{

// text view influenced by the Thread
private TextView threadModifiedText;
int time=0;
Button b1,b2,b3;
boolean shouldRun = false;
/** Called when the activity is first created. */
Thread currentThread = new Thread(this);
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stopwatch);

    b1=(Button)findViewById(R.id.button1);
    b2=(Button)findViewById(R.id.button2);
    b3=(Button)findViewById(R.id.button3);
    threadModifiedText = (TextView) findViewById(R.id.textView1);
    Log.e("before",""+currentThread.getState());
    b1.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View view) 
        {
            Log.e("stopw",(String) b1.getText());
            if(b1.getText().toString().equals("start")){
                    if(currentThread.getState()==Thread.State.NEW){
                        currentThread.start();
                        Log.e("after",""+currentThread.getState());
                        shouldRun = true;
                        b1.setText("pause");
                    }
                    else{
                      shouldRun = true;
                      b1.setText("pause");
                    }
            }
            else if(b1.getText().toString().equals("pause")){
                shouldRun = false;
                b1.setText("start");
            }
        }

    });     
    b2.setOnClickListener(new View.OnClickListener() 
    {
        public void onClick(View view) 
        {
            time=0;
        }

    });               
}


@Override
public void run(){
    try {
        while(shouldRun){
            Thread.sleep(1000);
            threadHandler.sendEmptyMessage(0);
        }
    } catch (InterruptedException e) {
    }   
}


private Handler threadHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        time++;
        threadModifiedText.setText(""+time);
    }
};

}

Upvotes: 0

Views: 199

Answers (2)

MByD
MByD

Reputation: 137322

You cannot start thread after it finishes it's job, and his state is no longer NEW anyway, you'll have to create a new thread in this case.

When you press "start" the second time, you reach this part:

else{
    shouldRun = true;
    b1.setText("pause");
}

And nothing in this code will make the thread run again of course...

Upvotes: 1

pumpkee
pumpkee

Reputation: 3357

I think your thread just runs to an end when you set shouldRun to false. Enclose your while loop into another while loop that is true as long as your program runs.

Upvotes: 0

Related Questions