Skip to content

Instantly share code, notes, and snippets.

@Priyansh-Kedia
Created September 3, 2021 18:53
Show Gist options
  • Save Priyansh-Kedia/57bf6c5d8c20f881fdbf09c181f67579 to your computer and use it in GitHub Desktop.
Save Priyansh-Kedia/57bf6c5d8c20f881fdbf09c181f67579 to your computer and use it in GitHub Desktop.
Link preview in Android
if (!url.contains("http")) {
url = "http://$url"
}
openGraphResult = OpenGraphResult()
try {
val response = Jsoup.connect(url)
.ignoreContentType(true)
.userAgent(AGENT)
.referrer(REFERRER)
.timeout(TIMEOUT)
.followRedirects(true)
.execute()
val doc = response.parse()
val ogTags = doc.select(DOC_SELECT_QUERY)
when {
ogTags.size > 0 ->
ogTags.forEachIndexed { index, _ ->
val tag = ogTags[index]
val text = tag.attr(PROPERTY)
when (text) {
OG_IMAGE -> {
openGraphResult!!.image = (tag.attr(OPEN_GRAPH_KEY))
}
OG_DESCRIPTION -> {
openGraphResult!!.description = (tag.attr(OPEN_GRAPH_KEY))
}
OG_URL -> {
openGraphResult!!.url = (tag.attr(OPEN_GRAPH_KEY))
}
OG_TITLE -> {
openGraphResult!!.title = (tag.attr(OPEN_GRAPH_KEY))
}
OG_SITE_NAME -> {
openGraphResult!!.siteName = (tag.attr(OPEN_GRAPH_KEY))
}
OG_TYPE -> {
openGraphResult!!.type = (tag.attr(OPEN_GRAPH_KEY))
}
}
}
}
} catch (e: Exception) {
e.printStackTrace()
launch(Dispatchers.Main) {
listener.onError(e.localizedMessage)
}
}
@yahyamahmudiy
Copy link

Where are the .xml codes and other activities? Can you share them too?

@Priyansh-Kedia
Copy link
Author

Hello @yahyamahmudiy
The xml codes and other activities are not relevant here.

Can you share your use case?

@ataballyyeva
Copy link

you didnt mention launch from what? launch(Dispatchers.Main) {
do you use coroutine or anything eles, can you specify it?

@Priyansh-Kedia
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment