0

I've been trying to create a java app that can print the current date and time into a csv file. But now I'm experiencing NullPointerException with the program. Can anyone help me to identify the problem? Thanks for the help!

import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;

public class Main {
    public Vector<String> log;
    
    public Vector getInstance(){
        if(log == null) {
            return new Vector<>();
        }
        return this.log;
    }
    
    public Main() {
        getInstance();
        
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        //masukin tanggal hari ini 5x
        Calendar cal = Calendar.getInstance();
        
        for(int i=0; i<5; i++) {
            log.add(dateFormat.format(cal.getTime()));
        }
        
        try {
            FileWriter csvWriter = new FileWriter("status.csv");
            for(int i=0; i<log.size(); i++) {
                csvWriter.append(log.get(i));
                if(i < log.size()-1) {
                    csvWriter.append("\n");
                }
            }
            
            System.out.println("Success write data!");
            csvWriter.flush();
            csvWriter.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

    public static void main(String[] args) {
        new Main();
    }

}

Error

Exception in thread "main" java.lang.NullPointerException
    at Main.<init>(Main.java:27)
    at Main.main(Main.java:50)

richard
  • 1
  • 1
  • 1
    What do you want to do at `if(log == null) { return new Vector<>(); }`? What is the goal of `getInstance()` method? – Pshemo Dec 10 '20 at 12:57
  • 1
    change your getInstance method to public void getInstance(){ if(log == null) { log = new Vector(); } } – tataelm Dec 10 '20 at 12:59
  • Ahh i see....that's the mistake. Thanks for the tips. – richard Dec 10 '20 at 13:16
  • 2
    I recommend you don’t use `DateFormat`, `SimpleDateFormat` and `Calendar`. Those classes are poorly designed and long outdated, the first two in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 10 '20 at 13:30

0 Answers0