Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Runnable return a value?

Is it possible for a Runnable to return a value? I need to do some intensive work on an Editable and then return it back. Here is my mock code.

public class myEditText extends EditText {
...
private Editable workOnEditable() {
    final Editable finalEdit = getText();
    Thread mThread = new Thread(new Runnable() {
        public void run() {


              //do work

              //Set Spannables to finalEdit

        }
     });
    mThread.start();
    return finalEdit;
}
...
}

So obviously my first problem is I'm trying to change finalEdit, but it has to be final in order to access it in and out of the thread, right? What's the correct way to do this?

like image 484
bwoogie Avatar asked Oct 21 '11 02:10

bwoogie


1 Answers

In Java, a Runnable cannot "return" a value.

In Android specifically, the best way to handle your type of scenario is with AsyncTask. It's a generic class so you can specify the type you want to pass in and the type that is returned to the onPostExecute function.

In your case, you would create an AsyncTask<Editable, Void, TypeToReturn>. Something like:

private class YourAsyncTask extends AsyncTask<Editable, Void, Integer> {
     protected Long doInBackground(Editable... params) {
         Editable editable = params[0];
         // do stuff with Editable
         return theResult;
     }

     protected void onPostExecute(Integer result) {
         // here you have the result
     }
 }
like image 83
spatulamania Avatar answered Sep 24 '22 19:09

spatulamania