Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Using CallBack properly in android studio

I have been stuck on this for past 2 days. I am testing if user has internet access with the callback.

Here is my code:

private void getForecast() {
        final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        final NetworkRequest.Builder builder = new NetworkRequest.Builder();

        assert connectivityManager != null;


        connectivityManager.registerNetworkCallback(
                builder.build(),
                new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(@NonNull Network network) {
                        super.onAvailable(network);
                        getDataFromAPI(latitude, longitude);
                    }

                    @Override
                    public void onUnavailable() {
                        super.onUnavailable();
                        showErrorMessage();
                    }
                }
        );
    }

I tested onAvailable method and it works fine. I can get data from API when I've access to the internet. However, I could not make onUnavailable work.

I tried to show some toasts when my wifi was turned off but it did not show anything. I tried logging but my log messages were not in the logcat. Maybe I am doing something wrong? is unAvailable method the one I should use when network is unavailable?

I've noticed that onUnavailable() checks unavailability based on timeout(Do not know anything about it) property. How to make my app see that connection is unavailable in terms of this timeout?

And also, do I have to unregister this network callBack? If so, how?