Pass data from thread into Activity

Posted by Laimoncijus on Stack Overflow See other posts from Stack Overflow or by Laimoncijus
Published on 2010-06-12T17:38:04Z Indexed on 2010/06/12 17:42 UTC
Read the original article Hit count: 220

Filed under:
|
|
|

Hi,

I am want to pass data back from a Thread to Activity (which created the thread).

So I am doing like described on Android documentation:

public class MyActivity extends Activity {

    [ . . . ]
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        [ . . . ]
    }

    protected void startLongRunningOperation() {

        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
                mResults = doSomethingExpensive();
                mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }

    private void updateResultsInUi() {

        // Back in the UI thread -- update our UI elements based on the data in mResults
        [ . . . ]
    }
}

Only one thing I am missing here - where and how should be defined mResults so I could access it from both Activity and Thread, and also would be able to modify as needed? If I define it as final in MyActivity, I can't change it anymore in Thread - as it is shown in example...

Thanks!

© Stack Overflow or respective owner

Related posts about android

Related posts about thread