-3

So, I was trying to add a class to an ArrayList, but when I do it gives me a Null Pointer Exception. I'm sure I am just overlooking a variable that I thought was initialized, but I can't figure it out.

This is the class:

enum WebType { GoogleResult, Webpage };
public class Webpage {

WebType type;

String pageName;
String content;
String url;
String MLA = "";

public Webpage(String pageName, String content, String url, WebType type){
    this.type = type;
    this.pageName = pageName;
    this.content = content;
    this.url = url;
    this.MLA = ""; // Temp
}

// TODO: Make Citation Maker

}

This is where I add the class to the ArrayList:

    public void Start(){
    for(Integer i = 0; i < tags.size(); i++){
        if(tags.get(i) == null)
            return;
        Webpage page = Google(tags.get(i));
        parseList.add(page); // The Error is on this line!
        log.append("Added " + page.url + " to parse list");
    }
    for(Integer i = 0; i < parseList.size(); i++){
        ParsePageCode(parseList.get(i));
    }
}

Here is the Google function, it googles whatever you tell it to and returns the page information:

    public Webpage Google(String search){
    String url = "https://www.google.com/search?q=" + search;
    String content = "";
    try {
        URLEncoder.encode(url, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.append("\n Unsupported Encoding Contacting Google");
    }
    try {
        content = GetPageCode(url);
    } catch (IOException e) {
        log.append("\n Unable To Reach Google");
        log.append(e.getMessage());
    }
    Webpage w = new Webpage("Google Result For " + search, content, url, WebType.GoogleResult);
    // System.out.println(search + url + WebType.GoogleResult);
    return w;
}

Any Ideas?

Wlliam
  • 165
  • 4
  • 11

2 Answers2

0

On the line that is throwing the exception, parseList is the only variable being dereferenced. The only other variable on that line is page, and it doesn't matter if page is null because you can add null elements to a List. So, it must be parseList causing the NPE.

jthomas
  • 224
  • 1
  • 5
-1

Actually there is no problem adding null to a collection of Objects. Retrieving the object and invoking its members later may cause NPE.

You have told is that the problem is on the line where you do add the object. The only way there to cause NPE is calling add() upon null. So that's your collection parseList that is not initialized yet. Maybe it's a field in the class and was never initialized to an actual object of type ArrayList, but it's only declared.

Royal Bg
  • 6,854
  • 1
  • 16
  • 24