我不知道为什么我在这段代码上得到空对象引用,这似乎很好,但是当我按下按钮并调用连接方法时,它必须给我用户的当前位置,但它挂起并跳出,这就是代码在我的片段类中,我已经向我的清单文件添加了权限,并且该应用程序具有必要的权限。
这不是重复的帖子我不知道为什么这里的人不首先注意重复的帖子答案只是为了避免应用程序不挂起即使在这里我们已经有权访问该位置但它返回无效的。
public class GalleryFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private EditText searchinput;
private Button searchbtn;
private JSONArray jsonArray;
private GoogleApiClient mLocationClient;
Location currentLocation;
@SuppressLint("ValidFragment")
public GalleryFragment(JSONArray array) {
// Required empty public constructor
this.jsonArray = array;
}
public GalleryFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
if (mLocationClient == null) {
mLocationClient = new GoogleApiClient.Builder(this.getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
searchinput = (EditText) rootView.findViewById(R.id.searchfld);
searchbtn = (Button) rootView.findViewById(R.id.searchbtn);
searchbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = searchinput.getText().toString();
mLocationClient.connect();
}
});
return rootView;
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i("salam", " Connected");
if(ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
}
Log.i ("salam ", " " + currentLocation.getLongitude());
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
日志:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“float android.location.Location.distanceTo(android.location.Location)”
更新:我通过使用正确的访问请求方式解决了我的问题
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) // grant the access from user when the activity created
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, // if the permission wasn't granted so ask for permission
PERMISSION_ACCESS_FINE_LOCATION);
} else { // if it was granted so get the location
getLocation();
}
}
然后:
@Override
public void onConnected(@Nullable Bundle bundle) { // this is an override method which will execute when we connect to client service of google
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { // if the permission was granted then get the location
LocationServices.FusedLocationApi.requestLocationUpdates( // update the location of user
mLocationClient, mLocationRequest, this);
// You need to ask the user to enable the permissions
LocationTracker tracker = new LocationTracker(getContext()) { // here we use a custom library name Location Tracer on github: https://github.com/quentin7b/android-location-tracker
@Override
public void onLocationFound(@NonNull Location location) {
currentLocation = location;
}
@Override
public void onTimeout() {
}
};
tracker.startListening();
if (currentLocation == null) {
currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
}
} else {
Toast.makeText(getContext(),"The application need to access your location TURN ON the Location Service and Restart the application",Toast.LENGTH_LONG).show();
}
}
最后通过这种方法管理请求:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
boolean allowed = true;
switch (requestCode) {
case PERMISSION_ACCESS_FINE_LOCATION:
// If request is cancelled, the result arrays are empty.
for (int res : grantResults) {
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
allowed = false;
break;
}
if (allowed) {
getLocation();
} else {
Toast.makeText(getContext(),"You need to 'Enable' the location service", Toast.LENGTH_SHORT).show();
}
}
祝你好运,谢谢