java - Google map Activity 在 "getLastKnownLocation"中崩溃

标签 java android google-maps

我的谷歌地图 Activity 到目前为止运行良好。我不知道发生了什么,但当调用“getLastKnownLocation”时应用程序崩溃了。我不明白为什么会发生这种情况,正如我之前所说,到目前为止一切都很好。

这是我得到的错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

这是我的 map Activity :

public class MapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;
    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;
    private ArrayList<User> userArrayList = new ArrayList<>();
    private User useri;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

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

                        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListener);

                    }

                }

            }

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mDatabase = FirebaseDatabase.getInstance().getReference();
        mAuth = FirebaseAuth.getInstance();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {


                LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());

                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("המיקום שלי"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));


            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        if (Build.VERSION.SDK_INT < 23) {

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        } else {

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

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

            }
            else {
                mMap.setMyLocationEnabled(true);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                mDatabase.child("Users").child(mAuth.getCurrentUser().getUid()).child("lat").setValue(lastKnownLocation.getLatitude());
                mDatabase.child("Users").child(mAuth.getCurrentUser().getUid()).child("lng").setValue(lastKnownLocation.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("המיקום שלי"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
            }
        }
        showUsersOnMap();

    }

    // Search for location and show it on the map
    public void onClick(View view) {

        if(view.getId() == R.id.searchLocationBtn){
            EditText searchBoxLocation = (EditText) findViewById(R.id.searchBoxLocation);
            String location = searchBoxLocation.getText().toString();
            List<Address> addressList = null;
            MarkerOptions markerOptions = new MarkerOptions();
            if( ! location.equals("")){
                Geocoder geocoder = new Geocoder(this);
                try {
                    addressList = geocoder.getFromLocationName(location, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                for (int i = 0 ; i < addressList.size(); i++){
                    Address myAddress = addressList.get(i);
                    LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
                    markerOptions.position(latLng);
                    mMap.clear();
                    mMap.addMarker(markerOptions);
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
                    searchBoxLocation.setText("");
                }
            }
        }
        showUsersOnMap();
    }

    // Function to show all the users on the map
    public void showUsersOnMap(){
        mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    User user = ds.getValue(User.class);
                    userArrayList.add(user);

                }

                for (int i = 0; i < userArrayList.size(); i++) {
                    useri = userArrayList.get(i);

                    if (useri.getLat() != 0  && useri.getLng() != 0) {
                        MarkerOptions markerOptions = new MarkerOptions();
                        LatLng userlatLng = new LatLng(useri.getLat(), useri.getLng());
                        markerOptions.position(userlatLng);
                        mMap.addMarker(new MarkerOptions().position(userlatLng).title(useri.getName()).snippet(useri.getPhone())
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_marker2)));
                        //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng2,10));

                    }
                    else Toast.makeText(getApplicationContext(),"ישנה בעיה. אנא נסה להתחבר למפה שוב",Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }


        });
    }
}

希望有人能找出问题所在。我搜索了同样的问题但没有成功。

最佳答案

将此行移至 oncreate 并检查

 locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

关于java - Google map Activity 在 "getLastKnownLocation"中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45939520/

相关文章:

java - 反转数组中元素的顺序

java - 将自定义 DialogFragment 绑定(bind)到初始化到应用程序范围的服务

java - 我想在长按 "+"或 "-"按钮时继续增加/减少计数器.... Android setOnLongClickListener

javascript - 将组合 JSON 文件加载到 Google map 上

javascript - 向谷歌地图添加复杂图标

java - 在 Tomcat 中替换类后常量不会改变

java - Vaadin 7 - 找不到请求的资源

android - 如何获取 ListView 的选定索引或位置并传递到新的 Activity 中?

android - map 聚类 - 最大缩放标记仍然聚类

java - 单击 Swing JTable 中的行时出现意外的事件顺序