Z
Z
Zirbi2015-01-28 10:26:01
Android
Zirbi, 2015-01-28 10:26:01

Error in Html parsing, how to fix?

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import java.net.URL;

public class MainActivity extends Activity {
    // HTML page
    static final String BLOG_URL = "https://yandex.ru/";
    // XPath query
    static final String XPATH_STATS = "//div[@id='blog-stats']/ul/li";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // init view layout
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // decide output
        String value = "";
        try {
            value = getBlogStats();
            ((TextView)findViewById(R.id.tv)).setText(value);
        } catch(Exception ex) {
            ((TextView)findViewById(R.id.tv)).setText("Error");
        }
    }

    /*
     * get blog statistics
     */
    public String getBlogStats() throws Exception {
        String stats = "";

        // config cleaner properties
        HtmlCleaner htmlCleaner = new HtmlCleaner();
        CleanerProperties props = htmlCleaner.getProperties();
        props.setAllowHtmlInsideAttributes(false);
        props.setAllowMultiWordAttributes(true);
        props.setRecognizeUnicodeChars(true);
        props.setOmitComments(true);

        // create URL object
        URL url = new URL(BLOG_URL);
        // get HTML page root node
        TagNode root = htmlCleaner.clean(url);

        // query XPath
        Object[] statsNode = root.evaluateXPath(XPATH_STATS);
        // process data if found any node
        if(statsNode.length > 0) {
            // I already know there's only one node, so pick index at 0.
            TagNode resultNode = (TagNode)statsNode[0];
            // get text data from HTML node
            stats = resultNode.getText().toString();
        }

        // return value
        return stats;
    }
}

Error exits

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2015-01-28
@GavriKos

After ((TextView)findViewById(R.id.tv)).setText("Error"); add Log.e("Error", ex);
This will print out the full exception for you and it will be clear what went wrong.

I
IceJOKER, 2015-01-28
@IceJOKER

try {
            value = getBlogStats();
            ((TextView)findViewById(R.id.tv)).setText(value);
        } catch(Exception ex) {
            ex.printStackTrace(); //ДАЛЕЕ ВЫЛОЖИТЕ ЛОГИ, вряд ли кому захочется вникаться в код
            ((TextView)findViewById(R.id.tv)).setText("Error");
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question