Swap
Swap

Reputation: 490

Android/Java - Wait for AsyncTask to end before performing next function

I'm creating an app which'll show a list of configured Wi-Fi networks in its MainActivity. Now, before fetching the list of configured networks, my app checks if Wi-Fi is turned on. If not, it shows an AlertDialog containing a "Turn on Wi-Fi" Button which triggers an AsyncTask that turns on the Wi-Fi.

Now, I'm using this code to fetch the list of configured Wi-Fi networks

@SuppressWarnings("deprecation")
private ArrayList<String> getAvailableNetworks() {

    manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    availableNetworks = new ArrayList<String>();

    if (!manager.isWifiEnabled()) {
        showDialog(2);
    }

    if (manager.isWifiEnabled()) {

        configuredNetworks = manager.getConfiguredNetworks();

        for (int i = 0; i < configuredNetworks.size(); i++) {
                    availableNetworks.add(configuredNetworks.get(i).SSID.replaceAll("\"", ""));
        }
    }

    return availableNetworks;
}

Now, the problem is that when the app finds out that the Wi-Fi is turned off, it just shows the AlertDialog using showDialog(2); and moves on to the next line of code which leaves the list of configured networks completely blank.

How do I get it to wait until the AsyncTask finishes turning on Wi-Fi before it moves on to the next line of code?

Thanks in Advance.

Upvotes: 0

Views: 294

Answers (1)

Sarthak Mittal
Sarthak Mittal

Reputation: 6094

You can start an Indeterminate Progress Dialog (unCancelable) at OnPreExecute and then dismiss it in onPostExecute

And if you don't want the code to get started executing before the asyncTask gets Completed, just put that code in onPostExecute method of AsyncTask

Upvotes: 1

Related Questions