Location.getLatitude()在null对象引用上

时间:2015-12-28 17:43:02

标签: java android parse-platform geolocation

我收到以下运行时错误: java.lang.NullPointerException:尝试在空对象引用上调用虚方法'double android.location.Location.getLatitude()'

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();

这是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();
            }

2 个答案:

答案 0 :(得分:2)

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

该位置为空,尚未初始化。

检查位置是否为空:

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

此外,您应该将所有位置服务代码包装成try并catch并检查空指针引用和连接,GPS提供商等。请查看此处BasicLocationSample

答案 1 :(得分:1)

我认为您应该调用此方法,它将返回您需要的内容。

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;
}