• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Location object, null object reference error

umtblbl

Member
Mar 6, 2019
50
5
Hi friends, I've created the following class.
Code:
public class Common {

    public static Location currentLocation;
}

I can see the location using Log.d in the activity I'm assigning a location to.

MainActivity.class (location assignment class)
Code:
private void BuildLocationCallBack() {
    locationCallback = new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);

            //Common.currentLocation = locationResult.getLastLocation();
            Common.currentLocation = new Location(locationResult.getLastLocation());

            Log.d("Location", Common.currentLocation.getLatitude()+"/"+Common.currentLocation.getLongitude());
        }
    };
}

Okey. But when I copy and paste the same line of Log.d over a different fragment, I get the following error;

TodayFragment.java
Code:
Log.d("Location",
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_today, container, false);

    Log.d("Location",Common.currentLocation.getLatitude()+"/"+Common.currentLocation.getLongitude()));

    return view;
}

Result;
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

Null object reference error. What could be the problem? Can you help me. Thank you.[/code]
 
Last edited:

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones