1

Hello I am trying to retrieve url, shared from another app and toast it as well as open it in WebViewTab. But instead id of the app is displayed in toast. here is my code:

  val extras = intent.extras
        if (extras != null) {
            for (key in activity.intent.extras!!.keySet()) {
                CopyKey = key

                val value: String? = activity.intent.extras!!.getString(CopyKey)
                Toast.makeText(applicationContext, value, Toast.LENGTH_LONG).show()
                    TabInfo.addTab(value.toString())
                
            }
            val url = intent.extras!!.getString("query")
            if (url.toString().startsWith("http")) {
                TabInfo.addTab(url.toString())
                intent.removeExtra("query")
            }
        }

Thanks in advance

2 Answers2

0

This solved my issue:

val extras = intent.extras
        if (extras != null) {
            val externalUrl: Uri? = intent?.data //retrieves the shared text from another app.
            val url = intent.extras!!.getString("query")
            if (url.toString().startsWith("http")) {
                TabInfo.addTab(url.toString())
                intent.removeExtra("query")
            }
            else {
                TabInfo.addTab(externalUrl.toString())
            }
        }
0

Check the detail below code snippets

Note:

  1. Error handling & data null check can be handled separately.
  2. Assuming success case.
    val URL_FINDER_REGEX = "((http:\\/\\/|https:\\/\\/|ftp:\\/\\/|file:\\/\\/)?(www.)?(([a-zA-Z0-9-]){2,2083}\\.){1,4}([a-zA-Z]){2,6}(\\/(([a-zA-Z-_\\/\\.0-9#:?=&;,]){0,2083})?){0,2083}?[^ \\n]*)"
    
    fun test(intent: Intent?) {

        intent?.let {
            it.extras?.let { extras ->
                val urlQuery = extras.getString("query")
                urlQuery?.let {
                    val links = getUrlsFromText(urlQuery)
                    println(links)
                    // TODO("Your Business logic")
                }
            }
        }
    }

    fun getUrlsFromText(text: String): ArrayList<URI> {

        val availableLinks = ArrayList<URI>()
        val matcher: Matcher = Pattern.compile(URL_FINDER_REGEX, Pattern.CASE_INSENSITIVE).matcher(text)
        while (matcher.find()) {
            try {
                val url = URI(matcher.group())
                availableLinks.add(url)
            } catch (e: Exception) {
                println(e)
            }
        }
        return availableLinks
    }

This is similar to some old queries.

Ref.

  1. Regular expression to find URLs within a string
  2. Detect and extract url from a string?
Sachin Shelke
  • 449
  • 4
  • 12