-3

I have a static arraylist defined in my loginactivity class.

private static ArrayList<LatLng> userCoordinates;

// Removed some code for ease of reading but the contents of the list are defined and set here:
ArrayList<LatLng> coords = new ArrayList<>();
                                            for (String lat: lats) {
                                                for (String lng: lngs) {
                                                    double a = Double.parseDouble(lat);
                                                    double b = Double.parseDouble(lng);
                                                    LatLng latLng = new LatLng(a,b);
                                                    coords.add(latLng);
                                                    break;
                                                }
                                            }
                                            setCoordinates(coords);

// Getter & Setter

private void setCoordinates(ArrayList<LatLng> coordinates) {
        userCoordinates = coordinates;
    }
    
    public static ArrayList<LatLng> getCoordinates() {
        return userCoordinates;
    }

However when I attempt to access this from another class and print it in the onCreate() method:

private ArrayList<LatLng> userCoordinates = LoginActivity.getCoordinates();

//In onCreate()
System.out.println(userCoordinates.toString());

I get the error: Attempt to invoke virtual method 'java.lang.String java.util.ArrayList.toString()' on a null object reference

Jonwil
  • 19
  • 4
  • 1
    You never initialize `userCoordinates`. You only give it a value if you call `setCoordinates()`, which is not done in the invoking code. – azurefrog Mar 22 '21 at 15:39
  • the getter is static, so the method cant be used outside that class. Remove `static`, it should work just fine – Criss Hills Mar 22 '21 at 15:39
  • Are you sure that the code initializing the list runs before the code getting the list? – Ole V.V. Mar 22 '21 at 15:43
  • @azurefrog `setCoordinates()` is called right after the `for` loop. – Ole V.V. Mar 22 '21 at 15:44
  • I do call setCoordinates() immediately after the loop. I've also done the exact same process for setting and getting a String (which is working fine) but for some reason the ArrayList is returning Null – Jonwil Mar 22 '21 at 15:51
  • @CrissHills That’s not so. A static method can easily be called from outside the class as long as it is public, which it is. It should be called with the syntax *classname.method()*, which the OP apparently also does: `LoginActivity.getCoordinates();`. – Ole V.V. Mar 22 '21 at 15:54

1 Answers1

-1

You need to call the code that initializes the array list.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Sara Bean
  • 139
  • 8