-1

I want to write a csv with the opencsv libary, however, when running the code I get a NullPointerException.

public void exportToCSV(ArrayList<Data> list) throws IOException {
        log.info("write CSV file");

        String writerPath = "C:\\Users\\User\\Desktop\\Output\\output.csv";

        CSVWriter writer = new CSVWriter(new FileWriter(writerPath), ';');

        //headers
                String [] entries = {"ID", "Date"};

        writer.writeNext(entries);

        List<String[]> data = new ArrayList<String[]>();
        for (int m = 0; m < list.size(); m++) {
            data.add(new String[] {
                    list.get(m).getID,
                    (list.get(m).getDate().toString()==null) ? "null" : list.get(m).getDate().toString(), //Here i get the NullPointerException
            });
        }
        writer.writeAll(data);
        writer.close();
    }

I guess that getDate() is null, which type is a Timestamp. However, why does my proposed solution not work in writing a String when getDate() is null.

I apprecaite your reply!

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • why you "guess". in which line was the exception thrown? did you use a debugger to see what is actually null? – gefei Nov 06 '14 at 07:25
  • Because is getDate() returns null, you can't call toString() on it. Duh. – JB Nizet Nov 06 '14 at 07:28
  • See also [`NullPointerException`](http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html), where almost the very first line of the documentation is "Calling the instance method of a null object." – Jason C Nov 06 '14 at 07:30

1 Answers1

1

list.get(m).getDate().toString()==null should be changed to list.get(m).getDate()==null.

If list.get(m).getDate() is null. Invoking a method on it will cause NullPointerException.

Jens
  • 67,715
  • 15
  • 98
  • 113
Chaitanya Gudala
  • 305
  • 1
  • 3
  • 22