NullPointerException- I don't know where

182 Views Asked by At

sorry for expanding NullPointerException flood :D

I have read tons of questions about NullPointerException but I can't figure out where is problem in my code.

problematic line:

if(userAgent.doc.innerHTML().contains("haha")

I tried String x = userAgent.doc.innerHTML(); and to use condition on the next line but is there is still: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.jaunt.Document.innerHTML()' on a null object reference

Please any idea what I did wrong?

Surrounding code:

private class AT extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            UserAgent userAgent = new UserAgent();
            toSearch += 50;
            while (visited.size() < toSearch) {
                try {
                    userAgent.visit(currentUrl);
                    Elements elements = userAgent.doc.findEvery("<a href>");
                    for (Element e : elements) {
                        String url = e.getAt("href");
                        if (!toVisit.contains(url) && !visited.contains(url) && url.contains(stayAt))
                            toVisit.add(url);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                visited.add(currentUrl);
                if(userAgent.doc.innerHTML().contains(key))
                    recipes.add(currentUrl);
                toVisit.remove(0);
                currentUrl = toVisit.get(0);
            }
            return null;
        }
    }

Thanks a lot for advice! :)

1

There are 1 best solutions below

1
On

you doc object in userAgent is null.

Add null check validation userAgent.doc != null while you try to add currentUrl in recipes :

 protected Void doInBackground(Void... voids) {
        UserAgent userAgent = new UserAgent();
        toSearch += 50;
        while (visited.size() < toSearch) {
            try {
                userAgent.visit(currentUrl);
                Elements elements = userAgent.doc.findEvery("<a href>");
                for (Element e : elements) {
                    String url = e.getAt("href");
                    if (!toVisit.contains(url) && !visited.contains(url) && url.contains(stayAt))
                        toVisit.add(url);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            visited.add(currentUrl);
            if(userAgent.doc != null && userAgent.doc.innerHTML().contains(key))
                recipes.add(currentUrl);
            toVisit.remove(0);
            currentUrl = toVisit.get(0);
        }
        return null;
    }