0

I'm trying to do something like this after clicking a button:

case R.id.bcheckConnection:
        if (IPok()) {
            PlcState.ErrPlc = false;
            Constant.adressIpPlc = adresIp.getText().toString();

            final ProgressDialog dialog =     ProgressDialog.show(Main.this, "", "Trying to connect...");
            new Thread(new Runnable() {
                public void run() {
                    timeout = network.testConnection(Constant.adressIpPlc, 102, 20000);
                    dialog.dismiss();
                }
            }).start();

            if (timeout > -1) {
                PlcState.ErrPlc = false;

                stanPolaczenia.setText("Connection established. Timeout = ");
                stanTimeout.setText(Long.toString(timeout));
                currentIp.setText(Constant.adressIpPlc);

            } else {
                PlcState.ErrPlc = true;
                stanPolaczenia.setText("Error");
                stanTimeout.setText("");
                currentIp.setText(Constant.adressIpPlc);
            }
        } else {
            Toast.makeText(Main.this, "Wrong IP", Toast.LENGTH_LONG).show();
        }
        break;

So is it possible to change text AFTER thread stops running?

iluvatar
  • 69
  • 1
  • 12

1 Answers1

1

You can use Thread.join() to block the current thread until the given thread is finished:

Thread myThread = new Thread(new Runnable() {
    public void run() {
       // Do something
    }
});
myThread.start();

// Do some things

// and block current thread until myThread is finished
myThread.join();

// Continue execution after myThread got finished

Edit: As @Eric already mentions in the question comments: for your (example) situation it seems to make more sense to use AsyncTask. It has two events (that are called on the UI thread), so you can update your UI with progress updates and when the task finished. For an AsyncTask example see: AsyncTask Android example

Community
  • 1
  • 1
Veger
  • 37,240
  • 11
  • 105
  • 116
  • 1
    Does that not defeat the whole purpose of doing something on another thread? – Cat Jan 03 '13 at 23:29
  • Before waiting on `myTHread` you can do all kind of things. Call `join()` after you are done and *really* need `myThread` to be finished. In my example, it indeed defaults the purpose of threads completely yes. I have updated my answer to make this (more) clear. – Veger Jan 03 '13 at 23:32