Search code examples
javaandroidandroid-asynctaskconnectioninetaddress

Check if website is available


I want to check if website is available. It works when website is available, but it crash everytime when you can't connect to the website. If there is problem with NetTask class.

    String netAddress = null;
    try
    {
        netAddress = new NetTask().execute("www.googlasdasdde.com").get();
        if(netAddress == null || netAddress == "" || netAddress.isEmpty()){
            Log.d("111", "brak sieci");
        } else {
            Log.d("111", "server działa");

        }
    }
    catch (Exception e1)
    {
        e1.printStackTrace();
    }

And NetTask:

public class NetTask extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... params)
    {
        java.net.InetAddress addr = null;
        try {
            addr = java.net.InetAddress.getByName(params[0]);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return addr.getHostAddress();
    }
}

Solution

  • public class NetTask extends AsyncTask<String, Integer, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            java.net.InetAddress addr = null;
            try {
                addr = java.net.InetAddress.getByName(params[0]);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            return addr.getHostAddress();
        }
    }
    

    Here, if you can't connect, the Exception is thrown, and you print the stacktrace.

    Right after that, you try to return the hostAddress member of addr, but addr is null in this case.

    either add a return statement in the try block, and return null after the try catch (or in the catch block), or throw an Exception in the catch block.