0

My program needs to take in a user's name as a String, and makes a call to the API to see if it exists. I made a method that takes in that string, and executes an async task to send the API call. But it looks like the comparison in my method is being executed before my async task finishes. What is the proper way to implement something like this

 public boolean checkUser(String name) {
    checkedName = name;
    checkValidSummoner check = new checkValidSummoner();
    check.execute();

    if (checkedName == null) {
        return false;
    } else {
        return true;
    }
}

private class checkValidSummoner extends AsyncTask<String, Void, Void> {
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Void doInBackground(String... strings) {
        try {
            checkedName = RiotAPI.getSummonerByName(checkedName).toString();
        } catch (APIException e) {
            checkedName = null;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {

    }
}
Brian Le
  • 159
  • 10
  • Don't return anything in that method. Run your task and do whatever is needed in `onPostExecute()`. See this answer http://stackoverflow.com/questions/18517400/inner-class-can-access-but-not-update-values-asynctask/18517648#18517648 – codeMagic Jan 04 '16 at 02:37
  • Is there any other way? I need the method to return a value, because I'll be using it elsewhere very frequently. – Brian Le Jan 04 '16 at 02:47

1 Answers1

0

You can't do that.
Please use listener.

public boolean checkUser(String name, OnCheckValidEndListener listener) {
    checkedName = name;
    checkValidSummoner check = new checkValidSummoner(listener);
    check.execute();


}

public interface OnCheckValidEndListener {
    void onCheckValidEnd(String checkedName);
}

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

    private final OnCheckValidEndListener listener;

    checkValidSummoner(OnCheckValidEndListener listener) {
        this.listener = listener;
    }
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Void doInBackground(String... strings) {
    try {
        checkedName = RiotAPI.getSummonerByName(checkedName).toString();
    } catch (APIException e) {
        checkedName = null;
    }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        listener.onCheckValidEnd(checkedName);

    }
}

And please use flowing code

    checkUser("jon",new OnCheckValidEndListener() {
        @Override
        public void onCheckValidEnd(String checkedName) {
            if (checkedName == null) {
                // invalid
            } else {
                // valid
            }
        }
    });
takahirom
  • 1,934
  • 2
  • 12
  • 21