I m experimenting with "new" libraries i found online by taking a close look at a covid tracing app. I scan a QR code, decode base64 to get the shop data in a Json string. I then use Gson to parse into a Shop POJO.
public class Shop {
public metadata metadata;
public String nameZh;
public String nameEn;
public String type;
public String hash;
public class metadata{
public String typeEn;
public String typeZh;
public String getTypeEn() { return this.typeEn; }
public String getTypeZh() { return this.typeZh; }
}
public metadata getMetadata() { return this.metadata; }
public String getNameZh() { return this.nameZh; }
public String getNameEn() { return this.nameEn; }
public String getType() { return this.type; }
public String getHash() { return this.hash; }
public String toString() {
return getMetadata().getTypeEn()+", "+getMetadata().getTypeZh()+", "
+getNameZh()+", "+getNameEn()+", "+ getType()+", "+getHash();
}
}
However, when i want to write into an excel file (.xlsx) using apache POI, I find that not all shops have all the fields, meaning that some are null. This is nullpointer exception i got.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Shop$metadata.getTypeEn()" because the return value of "Shop.getMetadata()" is null
at xlsxWorker.writeShop(xlsxWorker.java:77)
at xlsxWorker.writeOutput(xlsxWorker.java:51)
While it is possible for me to use try catch to avoid this, the resulting code has many try catch.
private static void writeShop(Row current, Shop shop){
Cell cell = current.createCell(0);
try{
cell.setCellValue(shop.getMetadata().getTypeEn());
}catch (NullPointerException e){
cell.setCellValue("null");
}
cell = current.createCell(1);
try{
cell.setCellValue(shop.getMetadata().getTypeZh());
}catch (NullPointerException e){
cell.setCellValue("null");
}
cell = current.createCell(2);
try{
cell.setCellValue(shop.getNameZh());
}catch (NullPointerException e){
cell.setCellValue("null");
}
cell = current.createCell(3);
try{
cell.setCellValue(shop.getNameEn());
}catch (NullPointerException e){
cell.setCellValue("null");
}
cell = current.createCell(4);
try{
cell.setCellValue(shop.getType());
}catch (NullPointerException e){
cell.setCellValue("null");
}
cell = current.createCell(5);
try{
cell.setCellValue(shop.getHash());
}catch (NullPointerException e){
cell.setCellValue("null");
}
}
How do I avoid the excessive use of try-catches here? How can I simplify the redundancies