Convert html parser with multiple divs from swift to android using Jsoup

367 Views Asked by At

I am trying to convert iOS application into android. But I just start learning Java a few days ago. I'm trying to get a value from a tag inside html.

Here is my swift code:

if let url = NSURL(string: "http://www.example.com/") {
        let htmlData: NSData = NSData(contentsOfURL: url)!
        let htmlParser = TFHpple(HTMLData: htmlData)


        //the value which i want to parse
        let nPrice = htmlParser.searchWithXPathQuery("//div[@class='round-border']/div[1]/div[2]") as NSArray

        let rPrice = NSMutableString()

        //Appending
        for element in nPrice {
            rPrice.appendString("\n\(element.raw)")
        }
        let raw = String(NSString(string: rPrice))

        //the value without trimming    
        let stringPrice = raw.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)

        //result
        let trimPrice = stringPrice.stringByReplacingOccurrencesOfString("^\\n*", withString: "", options: .RegularExpressionSearch)
}

Here is my Java code using Jsoup

public class Quote extends Activity {


    TextView price;
    String tmp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quote);


        price  = (TextView) findViewById(R.id.textView3);

        try {
            doc = Jsoup.connect("http://example.com/").get();

            Element content = doc.getElementsByTag("//div[@class='round-border']/div[1]/div[2]");
        } catch (IOException e) {
            //e.printStackTrace();
        }

    }
}

My problems are as following:

  1. I got NetworkOnMainThreatException whenever i tried any codes.
  2. I'm not sure that using getElementByTag with this structure is correct.

Please help, Thanks.

1

There are 1 best solutions below

2
Stephan On
  1. I got NetworkOnMainThreatException whenever i tried any codes.

You should use Volley instead of Jsoup. It will be a faster and more efficient alternative. See this answer for some sample code.

  1. I'm not sure that using getElementByTag with this structure is correct.
Element content = doc.getElementsByTag("//div[@class='round-border']/div[1]/div[2]");

Jsoup doesn't understand xPath. It works with CSS selectors instead. The above line of code can be corrected like this:

Elements divs = doc.select("div.round-border > div:nth-child(1) > div:nth-child(2)");

for(Element div : divs) {
    // Process each div here...
}