Billy Korsen
Billy Korsen

Reputation: 524

String.contains doing opposite Jsoup Android

I may be misunderstanding what String.contains does. I am now trying to pull a specific link using Jsoup in Android. I'm trying to just get the faceBook one as an example. Ive tried a few things. this one It Seems to be outputting got it on the ones that do not contain the facebook url and leaving the facebook ones blank. How do I just get the FaceBook ones and stop the loop.

protected Void doInBackground(Void... params) {
      Document doc = null;
         try {
             doc = Jsoup.connect("http://www.homedepot.com").get();
             Elements link = doc.select("a[href]");
             String stringLink = null;

             for (int i = 0; i < link.size(); i++) {

                 stringLink = link.toString();

                 if (stringLink.contains("https://www.facebook.com/")){
                     System.out.println(stringLink+"got it");
                 }
                 else{
                 //System.out.println(stringLink+"not it");
             }
             }
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }

         return null;
     }
   }

Upvotes: 0

Views: 51

Answers (1)

ashatte
ashatte

Reputation: 5538

The following line is causing the problem:

stringLink = link.toString();

The link variable is a collection of Elements (in this case every link on the page), so by calling link.toString() you're getting the String representation of every single link on the page all at once! That means stringLink will always contain the facebook link!

Change the line to:

stringLink = link.get(i).toString();

This line gets only the link at index i on each iteration and checks whether or not it contains the facebook link.

Upvotes: 2

Related Questions