skip to Main Content

Just as the title suggest, I have a problem with checking android connection to the server.

I have a project that I left for some month, back then the code that I used to check the server’s connection was the answer from this question, but now when I opened this project again and try to run it, I can’t seem to be able to reach the server.

This is my code to check the server’s connection :

public static boolean isServerConnected() {
    try {
        URL myUrl = new URL(URL_CONNECTION);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(10000);
        connection.connect();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

And this is where I call it (in a login button) :

btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (Servers.isServerConnected()) {
                username = edtUser.getText().toString();
                password = edtPass.getText().toString();
                login();
            } else {
                Toast.makeText(getApplicationContext(), "Server is not connected", Toast.LENGTH_SHORT).show();
            }
        }
    });

This is the exception that I got :

D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/System.err: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
    at java.net.Socket.connect(Socket.java:586)
    at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
    at com.android.okhttp.Connection.connectSocket(Connection.java:196)
    at com.android.okhttp.Connection.connect(Connection.java:172)
    at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
    at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
    at 
com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
    at 
com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
    at com.itats.huwenakapp.koneksi.Servers.isServerConnected(Servers.java:38)
    at com.itats.huwenakapp.Login$1.onClick(Login.java:74)
    at android.view.View.performClick(View.java:5610)
    at 
com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
    at android.view.View$PerformClick.run(View.java:22265)
W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

2

Answers


  1. As stated in the exception log you are getting android.os.NetworkOnMainThreadException this occurs when you are performing a network call on Main Thread / UI Thread of android. To resolve this issue you have to perform the call on a background thread. This could include using a AsyncTask (depricated) or Coroutines (only for Kotlin) or RxJava or any other threading way to run the the call on background thread.

    You can also check this question for answers.

    Login or Signup to reply.
  2. you got android.os.NetworkOnMainThreadException that means you cant check this with your main UI thread. you may have to create a new Thread.

    you may check like this in short:

        new Thread(new Runnable() {
            public void run() {
                Boolean connected = isServerConnected();
                YourActivityName.this.runOnUiThread(new Runnable() {
                    public void run() {
                        if(connected){
                            Log.e("isConnected", connected + " ");
                            //do your stuff
                        }
                    }
                });
            }
        }).start();
    
    
    // your found method 
    public static boolean isServerConnected() {
        try {
            URL myUrl = new URL(URL_CONNECTION);
            URLConnection connection = myUrl.openConnection();
            connection.setConnectTimeout(10000);
            connection.connect();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    

    make sure URL_CONNECTION is properly formatted

    Full Example:

          btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    public void run() {
                        Boolean connected = isServerConnected();
                        YourActivityName.this.runOnUiThread(new Runnable() {
                            public void run() {
                                if (connected) {
                                    Log.e("isConnected", connected + " ");
                                    //do your stuff
                                    username = edtUser.getText().toString();
                                    password = edtPass.getText().toString();
                                    login();
                                } else {
                                    Toast.makeText(getApplicationContext(), "Server is not connected", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                }).start();
    
    
            }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search