joshua
joshua

Reputation: 307

How find anchor Link from String?

I am new in Android now want how find anchor link tag from strings for example I have string like this which have some discrption and link

string product_distription="Buy this awesome " Thumb Design Mobile OK Stand Holder Universal For All 
here input
<a href="http://stackoverflow.com" >Buy now</a>

"
ouput: http://stackoverflow.com

Now only want extract link only from this string becuase I have app which have descrption link coming from PHP & MySQL and show in Android textview with link so now I only want know if discrption including any HTML anchor tag it will extract from the discrption only can extract not whole discrption only show this link

Upvotes: 2

Views: 1227

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79065

You can do it as follows:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(extractAnchorLinks(
                "This <a href=\"www.google.com\">search engine</a> is the most popular. This <a href=\"www.stackoverflow.com\"> website is the largest online community for developers</a>There are millions of websites today"));
    }

    public static List<String> extractAnchorLinks(String string) {
        List<String> anchorLinkList = new ArrayList<String>();
        final String TAG = "a href=\"";
        final int TAG_LENGTH = TAG.length();
        int startIndex = 0, endIndex = 0;
        String nextSubstring = "";
        do {
            startIndex = string.indexOf(TAG);
            if (startIndex != -1) {
                nextSubstring = string.substring(startIndex + TAG_LENGTH);
                endIndex = nextSubstring.indexOf("\">");
                if (endIndex != -1) {
                    anchorLinkList.add(nextSubstring.substring(0, endIndex));
                }
                string = nextSubstring;
            }
        } while (startIndex != -1 && endIndex != -1);
        return anchorLinkList;
    }
}

Output:

[www.google.com, www.stackoverflow.com]

The logic is straight forward. Moreover, the variable names are also self-explantory. Nevertheless, feel free to comment in case of any doubt.

Upvotes: 1

haresh
haresh

Reputation: 1420

 fun getLinkFromString() {
    val content = "visit this link: www.google.com"
    val splitted = content.split(" ")
    for (i in splitted.indices) {
        if (splitted[i].contains("www.") || splitted[i].contains("http://")) {
            println(splitted[i]) //just checking the output
            val link = "<a href=\"" + splitted[i] + "\">" + splitted[i] + "</a>"
            println(link)
            Toast.makeText(this, link, Toast.LENGTH_LONG).show()
        }
    }
}

This may help you to achieve similar.

Upvotes: 0

Related Questions