Search code examples
javacsvgoogle-distancematrix-api

java.lang.NullPointerException exception while reading csv file


I'm trying to calcule the distance and travel time between origins and destinations using the distance matrix API.

I used the following code :

 public class read_csv_file {
 public static ArrayList<String> getTownList(String fileName) {
    try {
        ArrayList<String> towns = new ArrayList<String>();
        File csvFile = new File(fileName);
        BufferedReader br = new BufferedReader(new FileReader(csvFile));
        String line = "";
        while ((line = br.readLine()) != null) {
            String[] arr = line.split(",");
            towns.add(arr[0]);
        }
        return towns;
    } catch (IOException ex) {
        ex.printStackTrace();
        System.out.println("Failed: could not find file.");
    }
    return null;
}
public static String getTown(ArrayList<String> towns) {
    int townsLen = towns.size();
    int rand = (int) (Math.random() * townsLen + 1);
    return towns.get(rand);
}
public static long getDriveDist(String origins, String destination) throws ApiException, InterruptedException, IOException {
    GeoApiContext distCalcer = new GeoApiContext.Builder()
            .apiKey("key")
            .build();
    DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(distCalcer);
    DistanceMatrix result = req.origins(origins)
            .destinations(destination)
            .mode(TravelMode.DRIVING)
            .avoid(DirectionsApi.RouteRestriction.TOLLS)
            .language("en-US")
            .await();
   long dist = result.rows[0].elements[0].distance.inMeters;
  return dist;
}
public static void main(String[] args) throws ApiException, InterruptedException, IOException {

    ArrayList<String> towns = getTownList("src/main/java/test_three.csv");

    if (towns != null) {
        // get 2 specific towns from the file
        // remove the first from ArrayList before getting the second
        String town1 = getTown(towns);
        towns.remove(towns.indexOf(town1));
        String town2 = getTown(towns);

        long dist = getDriveDist(town1, town2);

        // totalMinutes is based on walking at a speed of 10.6 minutes per km
        long totalMinutes = (long) (((dist / 1000) * 10.6));

        // calculate the days, hours and minutes from total minutes
        int days = (int) (totalMinutes / 24 / 60);
        int hours = (int) (totalMinutes / 60 % 24 );
        int minutes = (int) (totalMinutes / 60);

        // print
        System.out.println("It will take" + days + "days" + hours + "hours and" + minutes + "minutesto walk from"
                + town1 + "to"
                + town2 + ".");

    } else {
        System.out.println("Failed: null ArrayList for towns");
    }
   }}

But that throws :

Exception in thread "main" java.lang.NullPointerException
at line  "long dist = result.rows[0].elements[0].distance.inMeters;")

Example of My csv file :

Rochdale,Greater Manchester,North West
Lowestoft,Suffolk,South East
Kingston-upon-Thames,Greater London,London
Horley,Surrey,South East

I did some research and I found that the reason for this is that I am trying to access a table cell that does not exist for example tab [4] while the size of the table is 4 ,but I don't see here where the problem comes from. If you have any idea ,help me

Thank you.


Solution

  • There isn't sufficient information to be completely sure, but I suspect your problem is with the line:

    long dist = result.rows[0].elements[0].distance.inMeters
    

    I recommend checking each variable in that chain to see that there are actually values:

    if (null != result) {
      if (null != result.rows[0]) {
        if (null != result.rows[0].elements[0]) {
           // ... etc.  ...
        } else {
          System.out.println("ELEMENTS is null");
          return -1;
      } else {
        System.out.println("ROWS is null");
        return -1;
    } else {
      System.out.println("RESULT is null");
      return -1;
    }