gutenmorgenuhu
gutenmorgenuhu

Reputation: 2362

Java Singleton Method always nullpointer exception

I have a class called HtmlConnect.java. I declare the variable log as follows:

public Log log = Log.getInstance();

The Log.java file looks like this:

public class Log {

    private static Log instance = null;
    private String log;

    private Log() {

    }

    public static Log getInstance() {
        if (instance == null) {
            instance = new Log();
        }
        return instance;
    }

    public String getLog() {
        return log;
    }

    public void appendLog(String message) {
        this.log.concat(message+"\n");       
    }


    }

So when I call

log.appendLog("TestLog");

I always get a nullpointer exception. Why is taht?

Upvotes: 1

Views: 150

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533520

A simpler solution would be like this.

public enum Log {;

    private static final StringBuilder LOG = new StringBuilder();

    public static synchronized void append(String message) {
        LOG.append(message).append("\n");       
    }

    public static synchronized String getString() {
        return LOG.toString();
    }

    public static synchronized String getStringAndClear() {
        String s = LOG.toString();
        LOG.setLength(0);
        return s;
    }
}

which you can call with

Log.append("Hello");
Log.append("World");

String lines = Log.getStringAndClear();

Upvotes: 0

Prashant Thakkar
Prashant Thakkar

Reputation: 1403

Internally log.appendLog("TestLog"); uses log which is String and is not initialized.

Replace

private String log;

With

private String log = new String();

Upvotes: 1

StarsSky
StarsSky

Reputation: 6711

You need to initialize the log variable inside the constructor.

    private Log() {
      log = "";
    }

Upvotes: 5

Idan Arye
Idan Arye

Reputation: 12603

You forgot to initialize the log member field. You need to do it in the constructor.

Upvotes: 7

Related Questions