Blog Infos
Author
Published
Topics
,
Published

With the development of messaging applications, starting from WhatsApp for Chat Groups, to Slack for workspaces, link sharing is a crucial part.

WhatsApp provides a preview for the link that you enter in the input box, which helps users gain information about the content, without opening the link, increasing the user experience.

In this blog, we will see how we can create a preview like WhatsApp in Android.

The Open Graph protocol enables any web page to become a rich object in a social graph. While many different technologies and schemas exist and could be combined together, there isn’t a single technology which provides enough information to richly represent any web page within the social graph. The Open Graph protocol builds on these existing technologies and gives developers one thing to implement.

For building the code for link preview, we will be using the Open Graph Protocol.

We will start with creating the data class for the response from the link.

data class OpenGraphResult(
    var title: String? = null,
    var description: String? = null,
    var url: String? = null,
    var image: String? = null,
    var siteName: String? = null,
    var type: String? = null
)

In this data class, we add title, description, url, image, siteName, and type, all of this can be fetched using OGP. You can read more about the different fields here.

Now let us see how we can actually get some information from the link.

Let us start by adding some dependencies for Jsoup and Kotlin Coroutines.

implementation 'org.jsoup:jsoup:1.10.3'     
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

Jsoup is an open-source Java library designed to parse, extract, and manipulate data stored in HTML documents.

Now we start the code.

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)
}
}
view raw OgParser.kt hosted with ❤ by GitHub

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

We first check if the link contains, http or not, so as to make the link consistent.

Next, we connect to the url using Jsoup. Let us see what individual functions are meant for.

ignoreContentType :- True if you wish to ignore the type of content from the url. Unrecognised content might throw IOException.
userAgent :- Sets the request user-agent header
referrer :- Sets the request referrer header
timeout :- Sets the request timeout. IOException is thrown is timeout occurs
followRedirects :- True if you want the link to follow server redirects

Next, we parse the response and save it in a variable. We then select the CSS Query from this parsed data using doc.select(DOC_SELECT_QUERY).

We then iterate over the tags that we get and extract individual properties as per our requirements.

That is all you need to do to extract information from a link. This information can be shown to the user in any way possible.

You can find the variables used with Jsoup here.

private val AGENT = "Mozilla"
private val REFERRER = "http://www.google.com"
private val TIMEOUT = 10000
private val DOC_SELECT_QUERY = "meta[property^=og:]"
private val OPEN_GRAPH_KEY = "content"
private val PROPERTY = "property"
private val OG_IMAGE = "og:image"
private val OG_DESCRIPTION = "og:description"
private val OG_URL = "og:url"
private val OG_TITLE = "og:title"
private val OG_SITE_NAME = "og:site_name"
private val OG_TYPE = "og:type"
view raw VARNAMES.kt hosted with ❤ by GitHub

In this blog, we read about how one can implement OGP in android, to fetch information from the link.

You can also check out a small library I made for the same task. This library simplifies the task and gives the link information with just one line of code.

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
Modern mobile applications are already quite serious enterprise projects that are developed by hundreds…
READ MORE
blog
Ask yourself a fairly standard question for any interview to fill an Android position:…
READ MORE
blog
Kotlin Multiplatform Mobile (or simply Multiplatform Mobile) is a new SDK from JetBrains that…
READ MORE
blog
If you’ve been following my stories, this is the sequel of an article I’ve…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu