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);
}
}
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);
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With