Вопрос

I wrote this method:

@Override
    protected String call() {
        if (list != null) {
            int s = list.size();
            Metadata metadata;
            for (int i = 0; i < s; i++) {
                try {
                    File f = list.get(i);
                    metadata = ImageMetadataReader.readMetadata(f);
                    // obtain the Exif directory
                    ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
                    // query the tag's value
                    Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
                    if (date != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: " + sdf.format(date));
                    } else {
                        System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    System.out.println("Error: " + ex.getLocalizedMessage());
                } finally {
                    updateProgress(i + 1, s);
                }
            }
        }
        return null;
    }

Method directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL) can sometimes return null: Source

Problem is that by just calling that method java throws Null Pointer Exception, so I cannot test it with date!=null. NetBeans also reports "Dereferencing possible null pointer" hint. I do not understand why this happens. Why I'm not able to store null value in some object and test it? Even if I don't store value in variable, that method still causes the same exception when returning null.

Это было полезно?

Решение

One solution to this problem would be using another catch statement for NullPointerException, then calling the code you would call if the Date was null. You would also have to move variable "File f" out of the try-statement block to ensure access in the catch.

Example,

catch(NullPointerException e) {
    System.out.println("File: " + f.getAbsolutePath() + "\tDATETIME_ORIGINAL: no data!");
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top