简体   繁体   中英

Location.getLatitude() on a null object reference

I am getting the following Runtime Error: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ListView;

import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity {
    // Declare Variables
    ListView listview;
    List<ParseObject> ob;
    ProgressDialog mProgressDialog;
    ListViewAdapter adapter;
    Context context;
    private List<PlaceFilter> worldpopulationlist = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.activity_main);
        // Execute RemoteDataTask AsyncTask
        new RemoteDataTask().execute();
    }

    // RemoteDataTask AsyncTask
    private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Parse.com Custom ListView Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

Here is the ParseQuery

 try {
                // Locate the class table named "Country" in Parse.com
                ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                        "geo_filters");



                        // Locate the column named "ranknum" in Parse.com and order list
                // by ascending

                ob=query.find();
                for (ParseObject PlaceLocation : ob) {
                    // Locate images in flag column
                    ParseFile image = (ParseFile) PlaceLocation.get("FilterFile");
                    PlaceFilter map = new PlaceFilter();
                    ParseGeoPoint userLocation = new ParseGeoPoint(latitude, longitude);
                    query.whereNear("PlaceLocation", userLocation); //column as location
                    query.whereWithinKilometers("PlaceLocation", userLocation, 1);
                    map.setPlaceName((String) PlaceLocation.get("PlaceName"));
                    map.setFilterFile(image.getUrl());
                    worldpopulationlist.add(map);
                }
            } catch (ParseException e){
                Log.e("Error",e.getMessage());
                e.printStackTrace();
            }
 Runtime Error: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

The location is null, it has not been initialised.

Check that location is not null:

if(location!= null){
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
}

Also you should be wrapping all your location services code into a try and catch and be checking for null pointer references and connections, GPS providers etc. Have a look here BasicLocationSample .

I think you should call this method and it will return what you need.

private Location getLastKnownLocation() {
    Location l=null;
    LocationManager mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED) {
            l = mLocationManager.getLastKnownLocation(provider);
        }
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            bestLocation = l;
        }
    }
    return bestLocation;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM