开发者

Android: Starting Web Browser From Code

开发者 https://www.devze.com 2023-03-24 23:20 出处:网络
I am trying to open a web browser with a supplied url, however, after the last line of the following code, I get a null pointer exception.According to the call stack,Actvity.startActvitity(Intent) is

I am trying to open a web browser with a supplied url, however, after the last line of the following code, I get a null pointer exception. According to the call stack, Actvity.startActvitity(Intent) is where the exception occurs. This code is in a custom controller class for a sub view of the main activity. Any ideas on how to properly start the web browser via code, ideally from outside the main activity since I would to reuse as much as possible. or at least point me in the right direction.

private void showWebSite() {
            String _url = (String) this.开发者_JS百科urlview.getText();
            Activity webactivity = new Activity();
            Intent webIntent = new Intent( Intent.ACTION_VIEW );
            webIntent.setData( Uri.parse(_url) );
            webactivity.startActivity( webIntent );
    }


private void showWebSite() {
        String _url = (String) this.urlview.getText();
        //Activity webactivity = new Activity(); Not required
        Intent webIntent = new Intent( Intent.ACTION_VIEW );
        webIntent.setData( Uri.parse(_url) );
        this.startActivity( webIntent );
}

If you want it to be reusable create a static method like this

 public static void showWebSite(Activity activity, String url) {

        Intent webIntent = new Intent( Intent.ACTION_VIEW );
        webIntent.setData( Uri.parse(url) );
        activity.startActivity( webIntent );
}

/* Call from your activities like this */

CLASSNAME.showWebSite(this, (String) this.urlview.getText());


This won't work: you can't instantiate an Activity the way you have tried (Activity webactivity = new Activity(); will return a class that isn't properly setup by the Android framework, hence the null pointer exception).

You will have to pass in the original Activity to the function: something like this:

private void showWebSite(Activity webactivity) {
            String _url = (String) this.urlview.getText();
            Intent webIntent = new Intent( Intent.ACTION_VIEW );
            webIntent.setData( Uri.parse(_url) );
            webactivity.startActivity( webIntent );
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号