1

Hello everyone I am writing some simple code in order to open a webpage on an android device. Everything is fine but when I am trying to check whether the URL exists or not I am always getting the same error that the URL does not exist. Any help would be much appreciated. Many thanks.

So here is my code :

         public class MainActivity extends Activity
            {
       public static final String siteurl = "google.com";

       @Override
       public void onCreate(Bundle savedInstanceState)
        {
    final Context context = this;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Check Internet connectivity
    if (!exists(siteurl))
    {
        Toast.makeText(getApplicationContext(), "This site doesnt exist", Toast.LENGTH_LONG).show();
        TimedExit();
    }
    else
    {
        // Launch site
        startActivity(new Intent(context, WebViewActivity.class));
    }
        }

        public static boolean exists(String URLName)
        {
    try
    {
        HttpURLConnection.setFollowRedirects(false);
        // note : you may also need
        // HttpURLConnection.setInstanceFollowRedirects(false)
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return false;
    }
         }

       public void TimedExit()
        {
    TimerTask exitApp = new TimerTask()
    {
        @Override
        public void run()
        {
            System.exit(0);
        }
    };
    Timer timer = new Timer();
    timer.schedule(exitApp, new Date(System.currentTimeMillis() + 7000));
        }
            }

And my webviewactivity:

    public class WebViewActivity extends Activity
      {

private WebView webView;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true); // TODO: Check this warning
    webView.loadUrl(MainActivity.siteurl);
    webView.setWebViewClient(new WebViewClient());
}
    }

So the problem here is that everytime the program runs it returns that the URL does not exist. Any help would be grateful. Thank you.

user3449550
  • 123
  • 5
  • 17

1 Answers1

1

If you are trying to gain internet access from within your app you should add the proper permission tag in the manifest file, preferably before your application tag.

in this case:

<uses-permission android:name="android.permission.INTERNET" />

as showed in this thread.

i know is late, i hope it helps.

Community
  • 1
  • 1