Java 无法将LocationData获取到加载程序中
您好,我在我的项目中遇到了一个问题。我正在尝试获取用户位置,然后从URL中获取一些数据。但问题是,当我构建URL时,userLatitude和userLatitude显示为零。定位方法中没有问题,如我在OnMaReady部分中获取用户位置,但在中没有OnLoaderCreated part。我两个都需要它们 test1 textView的结果为0.0 0.0 从test2文本视图中可以看到我的坐标。 你能建议一个解决办法吗Java 无法将LocationData获取到加载程序中,java,android,loader,fusedlocationproviderapi,map-api,Java,Android,Loader,Fusedlocationproviderapi,Map Api,您好,我在我的项目中遇到了一个问题。我正在尝试获取用户位置,然后从URL中获取一些数据。但问题是,当我构建URL时,userLatitude和userLatitude显示为零。定位方法中没有问题,如我在OnMaReady部分中获取用户位置,但在中没有OnLoaderCreated part。我两个都需要它们 test1 textView的结果为0.0 0.0 从test2文本视图中可以看到我的坐标。 你能建议一个解决办法吗 public class MapActivity extends App
public class MapActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<List<Locations>>, OnMapReadyCallback {
public static final String LOG_TAG = MapActivity.class.getName();
private static final String URL="https://maps.googleapis.com/maps/api/place/nearbysearch/json";
private static final int LOCATION_LOADER_ID = 1;
private GoogleMap map;
private ProgressBar pb;
private TextView loadingTV;
private ArrayList<Locations> data;
private double userLongitude;
private double userLatitude;
private FrameLayout mapView;
FusedLocationProviderClient locationProviderClient;
int PERMISSION_ID = 44;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
permissionRequest();
locationProviderClient= LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
pb = (ProgressBar) findViewById(R.id.progressBar);
loadingTV = (TextView) findViewById(R.id.loadingTV);
mapView=(FrameLayout) findViewById(R.id.map);
mapView.setVisibility(View.GONE);
ConnectivityManager cm =
(ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
TextView noNetTV = (TextView) findViewById(R.id.noNetTV);
if (!isConnected) {
pb.setVisibility(View.GONE);
loadingTV.setVisibility(View.GONE);
} else {
noNetTV.setVisibility(View.GONE);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(LOCATION_LOADER_ID, null, this);
}
}
private boolean checkPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_ID
);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}
private void getLastLocation(){
if (checkPermissions()) {
if (isLocationEnabled()) {
locationProviderClient.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
userLatitude= location.getLatitude();
userLongitude= location.getLongitude();
}
}
}
);
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
);
}
@Override
public void onResume(){
super.onResume();
if (checkPermissions()) {
getLastLocation();
}
}
private void requestNewLocationData() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(0);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationProviderClient.requestLocationUpdates(
mLocationRequest, mLocationCallback,
Looper.myLooper()
);
}
private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
userLatitude= mLastLocation.getLatitude();
userLongitude= mLastLocation.getLongitude();
}
};
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
LatLng user = new LatLng(userLatitude,userLongitude);
**TextView test2=(TextView)findViewById(R.id.locations);
test2.setText(""+userLatitude+" "+userLongitude);**
Iterator<Locations> iterator=data.iterator();
while (iterator.hasNext()){
Locations loc=iterator.next();
LatLng marker=new LatLng(loc.getLatitude(),loc.getLongitude());
Toast.makeText(this,"Works",Toast.LENGTH_LONG).show();
map.addMarker(new MarkerOptions()
.position(marker)
.title(loc.getName()));
}
pb.setVisibility(View.GONE);
loadingTV.setVisibility(View.GONE);
// mapView.setVisibility(View.VISIBLE);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(user, 13));
// map.moveCamera(CameraUpdateFactory.newLatLng(user));
}
@Override
public Loader<List<Locations>> onCreateLoader(int i, Bundle bundle) {
String finalUrl=URL+"?"+"type=hospital"+"&key="+getString(R.string.google_maps_key)+"&radius=1500"+"&location="+userLatitude+","+userLongitude;
**TextView test1=(TextView)findViewById(R.id.locations);
test1.setText(""+userLatitude+" "+userLongitude);**
return new LocationAsyncTaskLoader(MapActivity.this,finalUrl);
}
@Override
public void onLoadFinished(android.content.Loader<List<Locations>> loader, List<Locations> locat) {
data=new ArrayList<>(locat.size());
data.addAll(locat);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onLoaderReset(android.content.Loader<List<Locations>> loader) {
// data.clear();
}
private void permissionRequest() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION },
1);
}
}
}
公共类MapActivity扩展了AppCompatActivity实现
LoaderManager.LoaderCallbacks,OnMapReadyCallback{
公共静态最终字符串LOG_TAG=MapActivity.class.getName();
私有静态最终字符串URL=”https://maps.googleapis.com/maps/api/place/nearbysearch/json";
私有静态最终int位置\u加载程序\u ID=1;
私人谷歌地图;
私人ProgressBar pb;
私有文本视图加载电视;
私有数组列表数据;
私人双用户;
私人双用户纬度;
私有框架布局地图视图;
FusedLocationProviderClient位置ProviderClient;
int PERMISSION_ID=44;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
许可请求();
locationProviderClient=LocationServices.getFusedLocationProviderClient(此);
getLastLocation();
pb=(ProgressBar)findViewById(R.id.ProgressBar);
loadingTV=(TextView)findViewById(R.id.loadingTV);
mapView=(FrameLayout)findViewById(R.id.map);
设置可见性(View.GONE);
连接管理器cm=
(ConnectionManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_服务);
NetworkInfo activeNetwork=cm.getActiveNetworkInfo();
布尔值isConnected=activeNetwork!=null&&
activeNetwork.isConnectedOrConnecting();
TextView noNetTV=(TextView)findViewById(R.id.noNetTV);
如果(!未连接){
pb.setVisibility(View.GONE);
加载电视设置可见性(视图已消失);
}否则{
noNetTV.SETVISION(视图已消失);
LoaderManager LoaderManager=getLoaderManager();
initLoader(LOCATION\u LOADER\u ID,null,this);
}
}
私有布尔检查权限(){
if(ActivityCompat.checkSelfPermission(此,Manifest.permission.ACCESS\u粗略位置)==PackageManager.permission\u已授予&&
ActivityCompat.checkSelfPermission(此,Manifest.permission.ACCESS\u FINE\u LOCATION)==PackageManager.permission\u已授予){
返回true;
}
返回false;
}
私有void requestPermissions(){
ActivityCompat.requestPermissions(
这
新字符串[]{Manifest.permission.ACCESS\u rough\u LOCATION,Manifest.permission.ACCESS\u FINE\u LOCATION},
许可证号
);
}
@凌驾
public void onRequestPermissionsResult(int-requestCode、字符串[]权限、int[]grantResults){
super.onRequestPermissionsResult(请求代码、权限、授权结果);
if(requestCode==权限\u ID){
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION\u已授予){
getLastLocation();
}
}
}
私有void getLastLocation(){
if(checkPermissions()){
如果(isLocationEnabled()){
locationProviderClient.getLastLocation().addOnCompleteListener(
新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
位置=task.getResult();
if(位置==null){
requestNewLocationData();
}否则{
userLatitude=location.getLatitude();
userLongitude=location.getLongitude();
}
}
}
);
}否则{
Toast.makeText(这个“打开位置”,Toast.LENGTH_LONG.show();
意向意向=新意向(设置、动作、位置、来源、设置);
星触觉(意向);
}
}否则{
请求权限();
}
}
私有布尔值isLocationEnabled(){
LocationManager LocationManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
返回locationManager.isProviderEnabled(locationManager.GPS|U提供程序)| | locationManager.isProviderEnabled(
LocationManager.NETWORK\u提供程序
);
}
@凌驾
恢复时公开作废(){
super.onResume();
if(checkPermissions()){
getLastLocation();
}
}
私有void requestNewLocationData(){
LocationRequest MLLocationRequest=新的LocationRequest();
mLocationRequest.setPriority(位置请求.优先级高精度);
mlLocationRequest.setInterval(0);
mlLocationRequest.SetFastTestInterval(0);
mLocationRequest.SetNumUpdate(1);
locationProviderClient=LocationServices.getFusedLocationProviderClient(此);
locationProviderClient.RequestLocationUpdate(
mLocationRequest、mLocationCallback、,
Looper.myLooper()
);
}
private LocationCallback mLocationCallback=new LocationCallback(){
@凌驾
public void onLocationResult(LocationResult LocationResult){
Location mLastLocation=locationResult.getLastLocation();
userLatitude=mLastLocation.getLatitude