Return value after Activity.runOnUiThread () method

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

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 Runnable.run()it is not possible to return a value after the method . But how to use (implement) another interface and return a value after execution.

Hope this is clear to everyone.

EDIT

May help someone else.

I use the D @Zapl solution and pass the parameter inside the class constructor Callable, for example:

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);
        }


    }
+4
source share
3 answers

If you really want to do this, you can use futures and Callable, roughly the same Runnable, but with a 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();

, call, get(),

    try {
        int returnValue = futureResult.get();
    } catch (ExecutionException wrappedException) {
        Throwable cause = wrappedException.getCause();
        Log.e("Error", "Call has thrown an exception", cause);
    }
+11

, final, runOnUiThread(), , . , runOnUiThread(), a String[], , String. , final

After executing the method, runOnUiThread()just assign the return value to yourarray[0], so after you can access it as soon as you exit the method.

---- EDIT ----

Example:

private void my_method() {
  final String[] your_array = new String[1];

  ...

  runOnUiThread(new Runnable() {

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

        your_array[0] = "Hello!!!";

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

  System.out.println("I've got a message! It says... " + your_array[0]);
}
0
source

Source: https://habr.com/ru/post/1524066/


All Articles