如何在Android中从Bundle加载URL

3

我无法使用从前一个Activity传递来的链接加载页面。

以下是代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_webpage);

    webView = (WebView) findViewById(R.id.webView);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    /*Bundle b = getIntent().getExtras();
    String url = b.getString(DeviceDetails.URL_KEY);*/

    String url = getIntent().getStringExtra(DeviceDetails.URL_KEY);
    //String url = "http://google.pl/nexus/4";
    webView.setWebViewClient(new MyWebViewClient());
    webView.loadUrl(url);
}


private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

当我使用String url="http://google.pl/nexus/4"时,一切似乎都很好。我非常确定我的活动从getIntent中获取了url,因为我进行了调试。
更新1:
String inputUrl = detUrlEditText.getText().toString();
Intent intent = new Intent(DeviceDetails.this, ShowWebPageActivity.class);
Bundle extras = new Bundle();
extras.putString(URL_KEY, inputUrl);
intent.putExtras(extras);
startActivity(intent);

上一个活动。我已经调试过了,所以保证可以传递url。而且toast也会在ShowWebPageActivity中显示传递的url。


1
你能展示一下发送链接的另一个活动吗? - Itzik Samara
值得注意的是,您正在使用 Intent 上的 Extra,这是与 Bundle 不同的概念。 - FoamyGuy
如果您注释掉下一行webView.setWebViewClient(new MyWebViewClient());,它是否能够正常工作?也许问题不在意图上。 - Itzik Samara
你能具体说明一下“我无法加载页面”吗?当它尝试加载时,屏幕上显示了什么?它是否强制关闭?在加载时,Logcat 中是否有任何信息输出?最后的猜测:你在清单文件中是否添加了“Internet”权限?如果忘记添加该权限,WebView 将会静默失败。 - FoamyGuy
具有互联网权限。WebView只显示白色页面。 - John
1个回答

0

不要在方法shouldOverrideUrlLoading()中调用view.loadUrl(url)

我在其他地方看到过这样的例子,但我不明白为什么,这是不必要的。

shouldOverrideUrlLoading()应该在您处理URL并且WebView不应加载它时返回true,并在WebView应继续加载URL时返回false。

如果您决定WebView应打开与URL参数不同的不同页面,则可以调用view.loadUrl()

以下是WebViewClient子类的示例:

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if (handleWithSystemBrowser(url)) {
           Uri webpage = Uri.parse(url);
           Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
           if (intent.resolveActivity(getPackageManager()) != null) {
               startActivity(intent);
           }
           return true;   // tells WebView that we specifically handled the URL, so don't load it
        }

        return false;   // go ahead and load it in the WebView
    }

    private boolean handleWithSystemBrowser(String url) {

        // put your code here to check the URL
        // return true if you want the device browser to display the URL
        // return false if you want the WebView to load the URL
        .
        .
        .
    }
}

现在它可以在浏览器中打开我的URL(String url =“http://google.pl/nexus/4”;)。当从先前的活动获取URL时,仍然是空白页面。 - John

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接