0

我试图获取 GPS 位置,但它显示以下错误

09-21 16:01:57.316: E/AndroidRuntime(8775): FATAL EXCEPTION: main
09-21 16:01:57.316: E/AndroidRuntime(8775): java.lang.NullPointerException
"09-21 16:01:57.316: E/AndroidRuntime(8775):    at com.mgrs.converter.pro.Geocoord.getLocation(Geocoord.java:26)"

我试图修复它,但我不知道如何纠正它。

请帮忙

MainActivity.java

public class MainActivity extends Activity {

    TextView site1_lat, site1_lon, site2_lat, site2_lon, distance_kilo, distance_miles, azimuth1_content, azimuth2_content;
    TextView current_lat, current_lon, current_mgrs_result;
    Variables vari;

    //for geoCoord
    //Context mContext;
    LocationManager mLocMan;
    String mProvider;
    //Location location;
    Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //for geoCoord
        //mLocMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //mProvider = mLocMan.getBestProvider(new Criteria(), true);
        //LocationListener mListener = new Geocoord();

        //mLocMan.requestLocationUpdates(mProvider, 6000, 10, mListener);
        //

    //Button 0
    Button btn = (Button)findViewById(R.id.btn);
    btn.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
        //1st site
        EditText mgrs_site1 = (EditText)findViewById(R.id.editText1);
        String site1 = mgrs_site1.getText().toString().toUpperCase();

        Converter converter = new Converter();
        Geocoord geocoord = new Geocoord();
        geocoord.getLocation(context);

        converter.MGRStoUTM(site1);

        ///get Lat, Longitude
        site1_lat = (TextView)findViewById(R.id.site1_lat);
        site1_lon = (TextView)findViewById(R.id.site1_lon);     
        site1_lat.setText(String.format("%6f", converter.getinitLat()));
        site1_lon.setText(String.format("%6f", converter.getinitLon()));

        //2nd site
        EditText mgrs_site2 = (EditText)findViewById(R.id.editText2);
        String site2 = mgrs_site2.getText().toString().toUpperCase();   
        converter.MGRStoUTM(site2);

        ///get Lat, Longitude
        site2_lat = (TextView)findViewById(R.id.site2_lat);
        site2_lon = (TextView)findViewById(R.id.site2_lon);     
        site2_lat.setText(String.format("%6f", converter.getinitLat()));
        site2_lon.setText(String.format("%6f", converter.getinitLon()));

        //current Lat, Longitude
        current_lat = (TextView)findViewById(R.id.current_lat);
        current_lon = (TextView)findViewById(R.id.current_lon);

        current_lat.setText(String.format("%6f", converter.getLatitude()));
        current_lon.setText(String.format("%6f", converter.getLongitude()));

        //get current MGRS
        String str;
        converter.LLtoMGRS(converter.getLatitude(),converter.getLongitude(),10);
        str=converter.getMGRS();
        System.out.println("MGRS result");
        System.out.println(str);

        current_mgrs_result = (TextView)findViewById(R.id.current_mgrs_result);
        current_mgrs_result.setText(str);


    }
    }); //ends button0

    //Button 1

    }//ends onCreate

}//ends Activity

Geocoord.java

public class Geocoord {
    Variables vari;
    Context mContext;
    LocationManager mLocMan;
    String mProvider;

    double latitude;
    double longitude;


    public void getLocation(Context context){
        mContext = context;
        mLocMan = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        mProvider = mLocMan.getBestProvider(new Criteria(), true);
        mLocMan.requestLocationUpdates(mProvider, 6000, 10, mListener);

    }

        LocationListener mListener =new LocationListener(){
          public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            setLatitude(latitude);
            setLongitude(longitude);
          }

        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            System.out.println("provider disabled");

        }
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            System.out.println("provider enabled");

        }
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
            System.out.println("status changed");
        }


    };


    public void setLatitude(double gps_latitude)
    {vari.gps_latitude = gps_latitude;}
    public void setLongitude(double gps_longitude)
    {vari.gps_longitude = gps_longitude;}

    public double getLatitude()
    {return vari.gps_latitude;}
    public double getLongitude()
    {return vari.gps_longitude;}


}
4

3 回答 3

0

您通过 Geocoord.getLocation(context) 传递上下文。但是这个上下文永远不会被初始化,并且是空的。

像这样传递 Activity 的 this 指针:

btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
    //1st site
    EditText mgrs_site1 = (EditText)findViewById(R.id.editText1);
    String site1 = mgrs_site1.getText().toString().toUpperCase();

    Converter converter = new Converter();
    Geocoord geocoord = new Geocoord();
    geocoord.getLocation(MainActivity.this); // use the MainActivitys context
    ...
}
}

现在您可以摆脱 Activity 中的 Context 字段,并且 NPE 应该消失了。

于 2013-09-21T09:41:40.477 回答
0

尝试使用这个GPS类,这对你更好。

 import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location = null; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
//              this.canGetLocation = false;
            } 

            else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     * */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * 
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }


    public void onLocationChanged(Location location) {
    }


    public void onProviderDisabled(String provider) {
    }


    public void onProviderEnabled(String provider) {
    }


    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


    public IBinder onBind(Intent arg0) {
        return null;
    }
}
于 2013-09-21T07:47:53.863 回答
0

NPE 是这些东西的常见问题,请尝试我发布的以下代码。

请记住 GPS 需要时间来加载,因此您可能需要重试 3-4 次,还要确保您在 mainfest 中添加了必要的权限

public Location getLocation() {
try {
    locationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

    // getting GPS status
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    // getting network status
    isNetworkEnabled = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isGPSEnabled && !isNetworkEnabled) {
        // no network provider is enabled
    } else {
        this.canGetLocation = true;
        if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network Enabled");
            if (locationManager != null) {
                location = locationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
            }
        }
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled) {
            if (location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("GPS", "GPS Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        }
    }

} catch (Exception e) {
    e.printStackTrace();
}

return location;

}

该代码对我有用,希望它也对你有用

于 2013-09-21T09:21:07.823 回答