首页 > 解决方案 > 我正在尝试使用 JAVA 从字符串中获取 URL

问题描述

我正在尝试使用 JAVA 从字符串中获取 URL。但我的变量在“Uri.parse”部分不起作用(变量中没有值)。请考虑我是编码初学者

错误是:“无法为最终变量‘result’赋值”

我的代码:

showResultDialogue(result.getContents());

..

public void showResultDialogue(final String result) {

        AlertDialog.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
        } else {
            builder = new AlertDialog.Builder(this);
        }


        Pattern p = Pattern.compile("[\\w\\.]+\\.(?:com|cc|net|ru|in)[^,\\s]*");
        Matcher m = p.matcher(result);


        builder.setTitle("Example Title")
                .setMessage("Text is " + result);


        if(m.matches()) {
            builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent browserIntent = new Intent(
                            Intent.ACTION_VIEW,
                            Uri.parse(result) // here is problem
                    );
                    startActivity(browserIntent);
                }
            });
        }

标签: javaandroidvariables

解决方案


由于您没有提供有关它为什么不起作用的信息,我只是假设 URL 丢失http,因为您的正则表达式不匹配,在这种情况下,我会这样做

编辑:你真的需要你的正则表达式吗?Android 有一种内置的 URL 匹配方式。

你可以在这里找到文档https://developer.android.com/reference/android/util/Patterns

Patterns.WEB_URL.matcher(result).matches();

所以你的代码看起来像这样

if (Patterns.WEB_URL.matcher(result).matches()) {
    builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent browserIntent = new Intent(
                Intent.ACTION_VIEW,
                Uri.parse(!result.startsWith("http://") && !result.startsWith("https://") ? "http://" + result : result)
            );
            startActivity(browserIntent);
        }
    });
}

推荐阅读