2

私は最初にこのコードに誤りがありました.Festusは、nullの場所があることを指摘しました:

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

私は Festus GPSTracker クラスを使用し、彼が示したようにアクティビティで使用しました。以下は私の活動クラスです:

package com.bob.terranet;

import java.util.List;

    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.net.Uri;
    import android.os.Bundle;

    public class Contactus extends Activity {

        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.contactus);

             double latitude = -1, longitude=-1;
              GPSTracker gps = new GPSTracker(Contactus.this);
              if (gps.canGetLocation()) {

                  latitude = gps.getLatitude();
                  longitude = gps.getLongitude();
        }





            String geoUriString = "http://maps.google.com/maps?" + 
                       "saddr=" + latitude + "," +  longitude + "&daddr=" + 33.947917 + "," + 35.645142;





            Intent mapCall = new Intent(Intent.ACTION_VIEW, Uri.parse(geoUriString));

                    startActivity(mapCall);
        }



    }

問題は、ネットワークに接続している間、ネットワーク プロバイダーが false であることを示す場所として常に -1、-1 が表示されることです。

4

3 に答える 3

2

あなたの場所はnullです

Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

この呼び出しはnullを返し、nullから値を取得しようとします==>

Caused by: java.lang.NullPointerException     03-15 11:25:50.855: E/AndroidRuntime(9992):     at com.bob.terranet.Contactus.onCreate(Contactus.java:22)

先に進む前に、現在地がnullでないかどうかを確認してください

GPS_providerが正しく機能しない場合があるため、常にbestProviderを使用することをお勧めします

Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

それでも問題が解決しない場合は、このクラスを使用してlonとlatを取得します

public class GPSTracker 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; // 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
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    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 Enabled", "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;
    }


    public void onLocationChanged(Location location) {
    }


    public void onProviderDisabled(String provider) {
    }


    public void onProviderEnabled(String provider) {
    }


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


}

これをあなたの活動に入れてください

 GPSTracker gps = new GPSTracker(Contactus.this);
      if (gps.canGetLocation()) {

         double latitude = gps.getLatitude();
         double longitude = gps.getLongitude();
}
于 2013-03-15T09:35:40.907 に答える
1

Manifast ファイルにパーミッションを追加しましたか?

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

あなたlastKnownLocationはnullであり、nullポインター例外を受け取るためにそこにあります。

次のコードを試して、最初の場所を取得してください。

List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();

if ((time > minTime && accuracy < bestAccuracy)) {
  bestResult = location;
  bestAccuracy = accuracy;
  bestTime = time;
}
else if (time < minTime && 
         bestAccuracy == Float.MAX_VALUE && time > bestTime){
  bestResult = location;
  bestTime = time;
}
}
}

ここから取得:

http://android-developers.blogspot.co.il/2011/06/deep-dive-into-location.html

このブログ記事も読むことをお勧めします...

基本的に、このコードは利用可能なすべてのプロバイダーを調べて、利用可能な最適な場所を取得します。

于 2013-03-15T09:28:52.173 に答える
1

この質問は何十回も聞かれました。GPS と LocationManager はイベント ドリブンであり、コールバックの原則に基づいて動作することに注意することが重要です。言い換えると、GPS が修正されて OnLocationChanged がトリガーされたときに位置を取得し、 の前ではありません。あなたは待たなければなりません。あなたがそれを手に入れることができないので、私が今その場所が欲しいと言うのは良くありません. OnLocationChanged が初めて発生するまで、 getLasKnownLocation は null になり、他の人が示しているように、それがエラーの原因です。

于 2013-03-15T11:14:37.013 に答える