Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return a value after Activity.runOnUiThread() method

Is it possible to return a value after Activity.runOnUiThread() method.

runOnUiThread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int var = SOMETHING;

        // how to return var value.         
    }
});

In this post i see that it's not possible to return a value after Runnable.run() method. But how to use (implement) another interface and return a value after execution.

Hope it's clear for all.

EDIT

May help someone else.

I useD @Zapl's solution, and passED a parameter inside the Callable class constructor, like this :

class MyCallable implements Callable<MyObject> {

        int param;

        public MyCallable (int param) {
            // TODO Auto-generated constructor stub
            this.param = param;
        }

        @Override
        public MyObject call() throws Exception {
            // TODO Auto-generated method stub
            return methodReturningMyObject(this.param);
        }


    }
like image 518
S.Thiongane Avatar asked Jan 28 '14 12:01

S.Thiongane


2 Answers

If you really want to do it you can use futures and Callable which is roughly a Runnable but with return value.

    final String param1 = "foobar";

    FutureTask<Integer> futureResult = new FutureTask<Integer>(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            int var = param1.hashCode();
            return var;
        }
    });


    runOnUiThread(futureResult);
    // this block until the result is calculated!
    int returnValue = futureResult.get();

This also works for exceptions thrown inside call, they will be re-thrown from get() and you can handle them in the calling thread via

    try {
        int returnValue = futureResult.get();
    } catch (ExecutionException wrappedException) {
        Throwable cause = wrappedException.getCause();
        Log.e("Error", "Call has thrown an exception", cause);
    }
like image 198
zapl Avatar answered Oct 01 '22 02:10

zapl


you can use handler to send message back.

check following example Android: When should I use a Handler() and when should I use a Thread?

like image 42
Ketan Parmar Avatar answered Oct 01 '22 03:10

Ketan Parmar