无法获取Fragment中的当前位置

时间:2016-09-15 12:44:24

标签: android nullpointerexception google-api-client google-location-services

我不知道为什么我在这段代码上得到空对象引用似乎很好但是当我按下按钮并调用connect方法时它必须给我当前用户的位置但它挂起并跳出来,这个是我的片段类的代码我已经将权限添加到我的Manifest文件,并且该应用程序具有必要的权限。

这不是一个重复的帖子我不知道为什么这里的人在重复的帖子中不首先注意答案只是为了避免申请不挂,即使在这里我们已经预先访问该位置但它返回null。

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();
        }
    }
祝你好运,谢谢

1 个答案:

答案 0 :(得分:0)

if(ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

    currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
}
Log.i ("salam ", "   " + currentLocation.getLongitude());

此时您已访问currentLocation以外的if block,当且仅当用户已授予相关权限时才会执行if block

您收到NullPointerException,因为用户未授予权限且此处未分配currentLocation

如果用户未授予权限,您可以使用

请求这些权限
ActivityCompat.requestPermissions(...)

并使用回调来了解他是否已授予权限并访问您的位置数据。

@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
}
相关问题