2

I am new to async tasks but I need to get a string from async task that is done in the background method for example

AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {

                    final MobileServiceList<AppDirectory> result =
                            mDirectoryTable.where().field("Family_Id").eq(11).execute().get();
                    for (AppDirectory item : result) {
                        //this is the string that I need to return
                         String neededstring = item.getheadofhousehold;
                    }
                } catch (final Exception e) {

                }
                return null;
            }
        };
//I need "neededstring" to equal result
        String result = task.execute();

2 Answers2

1

2 ways:

One is to use Interface as explained here: https://stackoverflow.com/a/12575319/1750013

Other one (quick and dirty), make a getters/setters in your Activity. In your onPostExecute(), set this string into the setter method.

Community
  • 1
  • 1
Rusheel Jain
  • 843
  • 6
  • 20
  • writing it from scratch for you wont be possible 1. make an interface (myInterface) with some function say public string abc() and also an attribute String myStr 2. in your activity that calls async task, assign this interface i.e. your activity must implement this interface and then before calling the async task write this: myInterface = this; 3. in the activity write the body of the abc() 4. in your onPostexecute(), first set the attribute of interface i.e. myInterface.myString = "value" and then make a call to abc() Hope it helps :) – Rusheel Jain Mar 15 '16 at 21:19
0

So you just return the string you want, and then get it back in on post execute when the task has ended or you can use on update proggress if you going on a loop or an array for example and want to return few strings 1 at a time.

here is an easy example:

 private class CustomTask extends AsyncTask<String, Void, String> {

    }

    @Override
    protected String doInBackground(String... params) {
       String str = "string i want to return";

        return str;
    }

    @Override
    protected void onPostExecute(String s) {
        String returned string = s;
    }
}
Roee
  • 1,155
  • 3
  • 15
  • 24