【问题标题】:I am trying to get URL from string using JAVA我正在尝试使用 JAVA 从字符串中获取 URL
【发布时间】:2018-11-17 14:52:24
【问题描述】:

我正在尝试使用 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);
                }
            });
        }

【问题讨论】:

  • 错误堆栈跟踪是什么?
  • @SamzSakerz 'result' 变量中没有任何内容
  • 如果有错误日志,您可以编辑您的问题吗?并将您在结果中输入的内容发送给我。
  • @SamzSakerz 输入是 "globalist.in/somthing.html" 。正则表达式匹配成功,但没有在浏览器中打开 url
  • 我明白了,你可以试试我的建议,看看是否有效?

标签: java android variables


【解决方案1】:

由于你没有提供它为什么不起作用的信息,我只是假设 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);
        }
    });
}

【讨论】:

  • 输入是 "globalist.in/somthing.html" 。正则表达式匹配成功,但没有在浏览器中打开 url
  • 没用。错误是:“无法为最终变量‘result’赋值”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 2020-06-20
  • 2021-10-01
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多