问题描述
我有一个片段,我想在其中获取当前坐标,然后使用Retrofit向Zomato Api发出请求,但我的当前位置返回null。我试图删除与我的api调用相关的代码,并且该应用返回了我正确的纬度和经度。我在做什么错?下面是我的java类。
我的片段
public class RestaurantsList extends Fragment {
private RestaurantAdapter mAdapter;
private RecyclerView mRecyclerView;
protected static List<Restaurant_> restaurantsList;
private Context context;
protected static OnRestaurantClickedListener listener;
private FirebaseAuth mAuth;
private static final int REQUEST_FINE_LOCATION=100;
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
private FusedLocationProviderClient mFusedLocationClient;
private Location myLocation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
mAuth = FirebaseAuth.getInstance();
restaurantsList= new ArrayList<>(50);
getLastLocation();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(),new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
myLocation=location;
Toast.makeText( getActivity(),"Latitude: "+location.getLatitude()+" Longitude: "+location.getLongitude(),Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(getActivity(),new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText( getActivity(),"It wasn´t possible to determine your location",Toast.LENGTH_SHORT).show();
}
});
getApi().getNearbyRestaurants(myLocation.getLatitude(),myLocation.getLongitude(),20,10000,"rating","desc","75be9f9e2239fe637bf9cb1b46979d91")
.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call,Response<ApiResponse> response) {
List<Restaurant> restaurants=response.body().getRestaurants();
mAdapter = new RestaurantAdapter(context,restaurantsList);
mRecyclerView.setAdapter(mAdapter);
RecyclerView.Itemdecoration itemdecoration = new DividerItemdecoration(context,DividerItemdecoration.VERTICAL);
mRecyclerView.addItemdecoration(itemdecoration);
for (int i = 0; i < restaurants.size(); i++) {
restaurantsList.add(restaurants.get(i).getRestaurant());
mAdapter.notifyItemInserted(i);
}
}
@Override
public void onFailure(Call<ApiResponse> call,Throwable t) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Couldn´t find any nearby restaurants");
AlertDialog mDialog = builder.create();
mDialog.show();
}
});
}
@Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View mContentView = inflater.inflate(R.layout.restaurants_list,container,false);
mRecyclerView = mContentView.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new linearlayoutmanager(mContentView.getContext()));
return mContentView;
}
@Override
public void onResume() {
super.onResume();
}
@Override public void onAttach(Activity activity) {
super.onAttach(activity);
try{
listener= (OnRestaurantClickedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonClicked");
}
}
private Retrofit getRetrofit(){
return new Retrofit.Builder()
.baseUrl("https://developers.zomato.com/api/v2.1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private ZomatoApi getApi(){
return getRetrofit().create(ZomatoApi.class);
}
private void getLastLocation(){
if (ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.ACCESS_FINE_LOCATION )!= PackageManager.PERMISSION_GRANTED) {
requestPermissions();
return;
}
}
private void requestPermissions(){
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_FINE_LOCATION);
}
}
新代码
public class RestaurantsList extends Fragment {
private RestaurantAdapter mAdapter;
private RecyclerView mRecyclerView;
protected static List<Restaurant_> restaurantsList;
private Context context;
protected static OnRestaurantClickedListener listener;
private FirebaseAuth mAuth;
private static final int REQUEST_FINE_LOCATION=100;
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
private FusedLocationProviderClient mFusedLocationClient;
private static final String TAG = "LOCATION";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
mAuth = FirebaseAuth.getInstance();
restaurantsList= new ArrayList<>(50);
getLastLocation();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
}
@Override public View onCreateView(LayoutInflater inflater,false);
mRecyclerView = mContentView.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new linearlayoutmanager(mContentView.getContext()));
return mContentView;
}
@Override
public void onResume() {
super.onResume();
}
@Override public void onAttach(Activity activity) {
super.onAttach(activity);
try{
listener= (OnRestaurantClickedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonClicked");
}
}
private Retrofit getRetrofit(){
return new Retrofit.Builder()
.baseUrl("https://developers.zomato.com/api/v2.1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private ZomatoApi getApi(){
return getRetrofit().create(ZomatoApi.class);
}
private void getLastLocation(){
if (ActivityCompat.checkSelfPermission(getContext(),REQUEST_FINE_LOCATION);
}
@Override
public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
if (requestCode == REQUEST_FINE_LOCATION) {
if (grantResults.length <= 0) {
// If user interaction was interrupted,the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG,"User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
getRestaurants();
}
}
}
private void getRestaurants(){
mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(),new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
getApi().getNearbyRestaurants(location.getLatitude(),location.getLongitude(),"75be9f9e2239fe637bf9cb1b46979d91")
.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call,Response<ApiResponse> response) {
List<Restaurant> restaurants=response.body().getRestaurants();
mAdapter = new RestaurantAdapter(context,restaurantsList);
mRecyclerView.setAdapter(mAdapter);
RecyclerView.Itemdecoration itemdecoration = new DividerItemdecoration(context,DividerItemdecoration.VERTICAL);
mRecyclerView.addItemdecoration(itemdecoration);
for (int i = 0; i < restaurants.size(); i++) {
restaurantsList.add(restaurants.get(i).getRestaurant());
mAdapter.notifyItemInserted(i);
}
}
@Override
public void onFailure(Call<ApiResponse> call,Throwable t) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Couldn´t find any nearby restaurants");
AlertDialog mDialog = builder.create();
mDialog.show();
}
});
}
}
}).addOnFailureListener(getActivity(),Toast.LENGTH_LONG).show();
}
});
}
}
解决方法
您正在执行两个异步任务,这些任务都将在将来的某个时刻完成(获取位置并进行Zomato API调用)。但是您在这里同时进行操作。即使位置代码在API调用代码之上,但实际上并没有在执行API调用之前等待位置。
您需要做的是将Zomato API调用移至其自己的方法。然后从FusedLocationProvider的constructor(public activateroute: ActivatedRoute,private configRegistry: CustomRegistry){
this.activateroute.params.subscribe((data: any) => {
console.log(data);
// this.key = data.key;
configRegistry.set('key',data.key);
});
}
elsewhere in another file
constructor(private configRegistry: CustomRegistry){
console.log(configRegistry.get('key'));
}
回调方法中调用此方法。这样,您就在等待使用该位置之前等待该位置。