0

Below is my code, i tried to implement interface to intercept respond from Connectivity Manager Network Callback, but Android Studio is throwing error at this interface internetListener.onInternetStatusUpdate(true) in onAvailable method.

I also implemented this interface at my main activity. I follow a few example too but failed. Is it that onAvailable method, my interface is not reachable?

public class CheckInternetAsyncTask extends ConnectivityManager.NetworkCallback
{
    private static final String TAG = "CheckInternetAsyncTask";
    private Context context;
    public InternetListener internetListener;
    private ConnectivityManager connectivityManager;
    private Network network;
    private NetworkCapabilities networkCapabilities;

    public interface InternetListener{
        void onInternetStatusUpdate(boolean hasInternet);
    }

    public CheckInternetAsyncTask(Context _context) {
        this.context = _context;
        this.connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(this);
        }

        try {
            new SendInternetRequest().execute().get(5, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    public void TestInternetRequest(){
        try {
            new SendInternetRequest().execute().get(5, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onAvailable(Network network) {
        super.onAvailable(network);
        this.network = network;

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            connectivityManager.bindProcessToNetwork(network);
            this.network = connectivityManager.getActiveNetwork();
        }else{
            ConnectivityManager.setProcessDefaultNetwork(network);
        }

        this.networkCapabilities = connectivityManager.getNetworkCapabilities(network);


        if(networkCapabilities != null && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)){
            internetListener.onInternetStatusUpdate(true);
        }else{
            try {
                new SendInternetRequest().execute().get(5, TimeUnit.SECONDS);
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

class SendInternetRequest extends AsyncTask<Void,Void, Void>{
    private static final String TAG = "SendInternetRequest";

    CheckInternetAsyncTask.InternetListener internetListener;

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            Socket sock = new Socket();
            sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
            sock.close();
            internetListener.onInternetStatusUpdate(true);

        } catch (IOException e) {
            internetListener.onInternetStatusUpdate(false);
        }

        return null;
    }
}

Stacktrace

2019-09-25 10:08:02.566 29555-29578/com.kioskactionandnotification E/AndroidRuntime: FATAL EXCEPTION: ConnectivityThread
    Process: com.kioskactionandnotification, PID: 29555
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.kioskactionandnotification.Model.Helper.CheckInternetAsyncTask$InternetListener.onInternetStatusUpdate(boolean)' on a null object reference
        at com.kioskactionandnotification.Model.Helper.CheckInternetAsyncTask.onAvailable(CheckInternetAsyncTask.java:85)
        at android.net.ConnectivityManager$NetworkCallback.onAvailable(ConnectivityManager.java:2770)
        at android.net.ConnectivityManager$CallbackHandler.handleMessage(ConnectivityManager.java:2969)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.os.HandlerThread.run(HandlerThread.java:65)

MainActivity.java

I implemented the interface

@Override
    public void onInternetStatusUpdate(boolean hasInternet) {
        this.hasInternet = hasInternet;
        Log.d(TAG, "onInternetStatusUpdate: hasInternet : "+hasInternet);
    }

That's all i have.

KIRPAL SINGH
  • 185
  • 2
  • 17
  • You're returning a void function? – BAS Sep 25 '19 at 01:44
  • @BAS You mean on async task do in background? Actually the compiler is complaining missing return statement. So i simply return null. since it is a void. But the error is not there. It happens in onAvailable method. internetListener.onInternetStatusUpdate(true); – KIRPAL SINGH Sep 25 '19 at 01:47
  • Returning `null` means you're returning something. You should return nothing `return;`Try that and see if it makes any difference. – BAS Sep 25 '19 at 01:51
  • @BAS No, compiler still throws missing return statement. But right now i am trying to solve why my interface is not reachable? – KIRPAL SINGH Sep 25 '19 at 01:52
  • oh I see, the function has a return type `Void` with capital `V` That is not the `void` keyword. – BAS Sep 25 '19 at 01:54
  • i tried this AsyncTask. Compiler says illegal type 'void'. Btw, I followed this example https://stackoverflow.com/questions/11194663/extending-asynctaskvoid-void-void and they use capital 'V' – KIRPAL SINGH Sep 25 '19 at 01:58
  • @BAS Any idea on the interface issue? Why is it not reachable? – KIRPAL SINGH Sep 25 '19 at 01:59
  • The error message you provided is not enough to tell what's the issue. Could you add more information we can work with? Like code, library, full error message, failed function parameters etc. – BAS Sep 25 '19 at 02:08
  • @BAS I have updated my code with all necessary information. I hope this will help. – KIRPAL SINGH Sep 25 '19 at 02:14

2 Answers2

0

It seems like you're trying to access an uninitialized object of type internetListener.

You need to initialize it:

internetListener = new InternetListener();

Or check if it was already initialized:

if (internetListener != null) {
 internetListener.onInternetStatusUpdate(true);
}

NOTE

Any abstract class you are using should be extended by a subclass that provides implementations for any of the abstract data/methods used from the abstract class.

Abstract class in Java

BAS
  • 145
  • 1
  • 11
  • InternetListener is a interface. It cant be initialized. I get error InternetListener is abstract. Cant be intantiated – KIRPAL SINGH Sep 25 '19 at 02:27
  • @KIRPALSINGH [Abstract class in Java](https://stackoverflow.com/questions/1320745/abstract-class-in-java) – BAS Sep 25 '19 at 02:46
  • The thing is mine is class that has an interface in it and not an abstract class. Neither am i extensing an abstract class. So i am not quite sure what is happening here. – KIRPAL SINGH Sep 25 '19 at 02:49
  • where `InternetListener` is imported from? – BAS Sep 25 '19 at 02:54
  • Its in my code above. public interface InternetListener{ void onInternetStatusUpdate(boolean hasInternet); } – KIRPAL SINGH Sep 25 '19 at 02:55
0

In my constructor below, i added a listener. Its basically my interface.

public CheckInternetAsyncTask(Context _context, InternetListener internetListener) {
    this.context = _context;
    this.internetListener = internetListener;

}

Then in my main activity where i am implementing this interfaces, I had to push "this" keyword, to my listener. I am still studying the difference between context and "this" keyword and how they work on interfaces

new CheckInternetAsyncTask(context, this);

Reference: How to create our own Listener interface in android?

KIRPAL SINGH
  • 185
  • 2
  • 17