传递到url时用户位置坐标为空

问题描述:

我正在使用开放天气地图API构建一个简单的五天天气预报Android应用程序。我正尝试使用Google Play服务将用户坐标插入到我的请求网址中,但当我将它们传递到网址时,纬度和经度值为空。我只是想知道是否有任何方法通过传递来自Google Play服务的onConnected方法的坐标来解决此问题。传递到url时用户位置坐标为空

MainActivity

public class MainActivity extends AppCompatActivity implements OnConnectionFailedListener { 

private GoogleApiClient mGoogleApiClient; 
private Location mLastLocation; 
private String latitude; 
private String longitude; 
private String requestUrl = "http://api.openweathermap.org/data/2.5/forecast?lat="+latitude+"&lon="+longitude+"&units=metric&APPID={insert api key here}"; 

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

    // Create an instance of GoogleAPIClient. 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

    new WeatherAsyncTask().execute(requestUrl); 
} 

public void updateUi(final ArrayList<Weather> weather) { 
    // Find a reference to the {@link ListView} in the layout 
    ListView weatherListView = (ListView) findViewById(R.id.list); 

    // Create a new {@link ArrayAdapter} of earthquakes 
    WeatherAdapter adapter = new WeatherAdapter(this, weather); 

    // Set the adapter on the {@link ListView} 
    // so the list can be populated in the user interface 
    weatherListView.setAdapter(adapter); 
} 

private class WeatherAsyncTask extends AsyncTask<String, Void, ArrayList<Weather>> { 
    protected ArrayList<Weather> doInBackground(String... requestUrl) { 
     // Dont perform the request if there is no URL, or first is null 
     if (requestUrl.length < 1 || requestUrl[0] == null) { 
      return null; 
     } 

     ArrayList<Weather> weather = QueryUtils.fetchWeatherData(requestUrl[0]); 

     return weather; 
    } 

    protected void onPostExecute(ArrayList<Weather> weather) { 
     // if there is no result do nothing 
     if (weather == null) { 
      return; 
     } 

     updateUi(weather); 
    } 
} 

// if connection not established to google play services 
@Override 
public void onConnectionFailed(ConnectionResult result) { 
    // An unresolvable error has occurred and a connection to Google APIs 
    // could not be established. Display an error message, or handle 
    // the failure silently 

    // ... 
} 

// get latitude and longitude of last known location when connected to google play services 
public void onConnected(Bundle connectionHint) { 
    try { 
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    } catch (SecurityException e) { 
     Log.e("MainActivity", "Security exception thrown", e); 
    } 
    if (mLastLocation != null) { 
     latitude = String.valueOf(mLastLocation.getLatitude()); 
     longitude = String.valueOf(mLastLocation.getLongitude()); 
    } 
} 

}

当运行应用程序,我得到一个NullPointerException。我意识到纬度和经度的值为空,但我不知道如何正确检索它们。感谢您的帮助,我在android开发方面相当新颖。

P.S.我从URL

省略API密钥,请参阅本指南:Retrieving-Location-with-LocationServices-API

所有LocationServices.FusedLocationApi.getLastLocation首先将返回一个位置,如果任何最近应用程序使用的位置(设备具有最近的位置),否则将返回null

所以在空值的情况下,您必须在onConnected内检查它。 为了得到非空位置你必须听设备的位置。(FusedLocationApi,...的LocationManager)

你也必须检查权限Android M更高版本的设备,幸运的是你正在使用FusedLocationApiActivity内。

我的代码基本示例:

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    if(HelperUtils.isGpsOpen(getApplicationContext())) { 
     startListenLocation(); 
    } 
} 

@Override 
public void startListenLocation() { 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     //ask permission whatever you want to do 
    } else { 
     if(mGoogleApiClient==null) { 
      buildGoogleApiClient(); 
     } else { 
      if(mGoogleApiClient.isConnected()) { 
       mLocationRequest = new LocationRequest(); 
       mLocationRequest.setInterval(UPDATE_INTERVAL); 
       mLocationRequest.setFastestInterval(FASTEST_INTERVAL); 
       mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
       mLocationRequest.setSmallestDisplacement(DISPLACEMENT); 
       Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
       //here I am checking null thats where you get null 
       if(mCurrentLocation!=null) { 
        mPresenter.onNewLocation(getDeviceId(),mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude()); 
       } 
       // then I am tracking user location , this will trigger onLocationChanged method when a new location arrived so you can handle new location 
       LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
      } else { 
       if(!mGoogleApiClient.isConnecting()) 
       buildGoogleApiClient(); 
      } 
     } 

    } 

} 

@Override 
public void onLocationChanged(Location location) { 
    // I am just checking null again, more cautious I am :) 
    if(location!=null) // handle it 
} 

那么重要的部分是删除位置请求时,你Activity'sonDestroy

if(mGoogleApiClient!=null){ 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     if(mGoogleApiClient.isConnected()) mGoogleApiClient.disconnect(); 
} 
+0

我已经实现了位置,但纬度和经度字符串为null当传递给requestUrl时。为什么是这样 ?谢谢 –

+0

@KeelanByrne你对你的清单有合适的权限 –

+0

这些是我的权限 –