1

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?

3
  • 2
    Maybe you are trying to appendLog without first have instantiate the log. Commented Jan 4, 2014 at 20:09
  • 1
    Use a logging framework, never try and implement logging yourself. This just leads to grief for everyone involved. Commented Jan 4, 2014 at 20:15
  • This this.log.concat(message+"\n"); returns the result. Discarding the result won't do anything. Commented Jan 4, 2014 at 21:07

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

Comments

5

You need to initialize the log variable inside the constructor.

    private Log() {
      log = "";
    }

Comments

1

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

Replace

private String log;

With

private String log = new String();

1 Comment

Instead of new String() use just "";
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.