我收到以下错误

时间:2018-06-14 17:02:45

标签: object methods null double

我收到以下错误:java.lang.NullPointerException:尝试调用虚方法' double android.location.Location.getLatitude()'在空对象引用上

这是Logcat

java.lang.NullPointerException:尝试调用虚方法' double android.location.Location.getLatitude()'在空对象引用上

    at com.example.shibli.luxuryrider.Home.requestPickupHere(Home.java:338)
    at com.example.shibli.luxuryrider.Home.access$000(Home.java:96)
    at com.example.shibli.luxuryrider.Home$2.onClick(Home.java:217)
    at android.view.View.performClick(View.java:4848)
    at android.view.View$PerformClick.run(View.java:20300)
    at android.os.Handler.handleCallback(Handler.java:815)
    at android.os.Handler.dispatchMessage(Handler.java:104)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5682)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)

这个代码..请帮忙

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mService = Common.getFCMService();

    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    //init storage
    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    View navigationHeaderView = navigationView.getHeaderView(0);
    txtRiderName = navigationHeaderView.findViewById(R.id.txtRiderName);
    txtRiderName.setText(String.format("%s", Common.currentUser.getName()));
    txtStars = navigationHeaderView.findViewById(R.id.txtStars);
    txtStars.setText(String.format("%s", Common.currentUser.getRates()));
    imageAvatar = navigationHeaderView.findViewById(R.id.imageAvatar);

    //Load avatar
    if (Common.currentUser.getAvatarUrl() != null && !TextUtils.isEmpty(Common.currentUser.getAvatarUrl())) {
        Picasso.with(this)
                .load(Common.currentUser.getAvatarUrl())
                .into(imageAvatar);
    }

    //Maps
    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    //Geo Fire
    ref = FirebaseDatabase.getInstance().getReference("Drivers");
    geoFire = new GeoFire(ref);

    //init View
    imgExpandable = (ImageView)findViewById(R.id.imgExpandable);
    mBottomSheet = BottomSheetRiderFragment.newInstance("Rider bottom sheet");
    imgExpandable.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mBottomSheet.show(getSupportFragmentManager(),mBottomSheet.getTag());

        }
    });

     btnPickupRequest = (Button) findViewById(R.id.btnPickupRequest);
     btnPickupRequest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (!Common.isDriverFound)
               requestPickupHere(FirebaseAuth.getInstance().getCurrentUser().getUid());
            else
                sendRequestToDriver(Common.driverId);
        }
    });

    place_destination = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_destination);
    place_location = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_location);
    typeFilter = new AutocompleteFilter.Builder()
            .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
            .setTypeFilter(3)
            .build();

    //Event
    place_location.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {

            mPlaceLocation = place.getAddress().toString();

            //Remove Old Marker
            mMap.clear();

            //Add Marker at New Location
            mUserMarker = mMap.addMarker(new MarkerOptions().position(place.getLatLng())
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
                    .title("Pickup Here"));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));

        }

        @Override
        public void onError(Status status) {

        }
    });
    place_destination.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            mPlaceDestination = place.getAddress().toString();

            //Add New destination Marker
            mMap.addMarker(new MarkerOptions()
                    .position(place.getLatLng())
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
                    .title("Destination"));


            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));

           // Show information in bottom
            BottomSheetRiderFragment mBottomsheet = BottomSheetRiderFragment.newInstance(mPlaceLocation);
            mBottomsheet.show(getSupportFragmentManager(), mBottomsheet.getTag());
        }

        @Override
        public void onError(Status status) {

        }
    });

    setUpLocation();

    updateFirebaseToken();
}

private void updateFirebaseToken() {
    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference tokens = db.getReference(Common.token_tb1);

    Token token = new Token(FirebaseInstanceId.getInstance().getToken());
    tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
            .setValue(token);

}

private void sendRequestToDriver(String driverId) {
    DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.token_tb1);

    tokens.orderByKey().equalTo(driverId)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot postSnapShot : dataSnapshot.getChildren()) {
                        Token token = postSnapShot.getValue(Token.class);

                        //Make raw payload
                        String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
                        String riderToken = FirebaseInstanceId.getInstance().getToken();
                        Notification data = new Notification(riderToken, json_lat_lng);
                        Sender content = new Sender(token.getToken(), data);

                        mService.sendMessage(content)
                                .enqueue(new Callback<FCMResponse>() {
                                    @Override
                                    public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
                                        if (response.body().success == 1)
                                            Toast.makeText(Home.this, "Request sent", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(Home.this, "Failed", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onFailure(Call<FCMResponse> call, Throwable t) {
                                        Log.e("ERROR", t.getMessage());

                                    }
                                });
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}

private void requestPickupHere(String uid) {
    DatabaseReference dbRequest = FirebaseDatabase.getInstance().getReference(Common.pickup_request_tb1);
    GeoFire mGeoFire = new GeoFire(dbRequest);
    mGeoFire.setLocation(uid, new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));

    if (mUserMarker.isVisible())
        mUserMarker.remove();

    //Add new Marker
    mUserMarker = mMap.addMarker(new MarkerOptions()
            .title("Pickup Here")
            .snippet("")
            .position(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()))
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
    mUserMarker.showInfoWindow();

    btnPickupRequest.setText("Getting your Driver...");

    findDriver();


}
 private void findDriver() {
    final DatabaseReference drivers = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
    GeoFire gfDrivers = new GeoFire(drivers);

    final GeoQuery geoQuery = gfDrivers.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()), radius);

    geoQuery.removeAllListeners();
    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
        @Override
        public void onKeyEntered(String key, GeoLocation location) {

            // if found
            if (!Common.isDriverFound) {
                Common.isDriverFound = true;
                Common.driverId = key;
                btnPickupRequest.setText("CALL DRIVER");
                Toast.makeText(Home.this, ""+key, Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onKeyExited(String key) {

        }

        @Override
        public void onKeyMoved(String key, GeoLocation location) {

        }

        @Override
        public void onGeoQueryReady() {
            //if still not found driver , increase distance
            if (!Common.isDriverFound && radius < LIMIT) {
                radius++;
                findDriver();
            } else {
                if (!Common.isDriverFound) {
                    Toast.makeText(Home.this, "No available any driver near you", Toast.LENGTH_SHORT).show();
                    btnPickupRequest.setText("REQUEST PICKUP");
                    geoQuery.removeAllListeners();
                }
            }

        }

        @Override
        public void onGeoQueryError(DatabaseError error) {

        }
    });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setUpLocation();
            }
            break;
    }
}

private void setUpLocation() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //Request runtime permission
        ActivityCompat.requestPermissions(this, new String[]{
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION

        }, MY_PERMISSION_REQUEST_CODE);
    } else {
            buildLocationCallBack();
            createLocationRequest();
            displayLocation();
        }

}

private void buildLocationCallBack() {
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            Common.mLastLocation = locationResult.getLocations().get(locationResult.getLocations().size() - 1);
            displayLocation();
        }
    };
}

private void displayLocation() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            Common.mLastLocation = location;
            if (Common.mLastLocation != null) {

                LatLng center = new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude());

                LatLng northSide = SphericalUtil.computeOffset(center, 100000, 0);
                LatLng southSide = SphericalUtil.computeOffset(center, 100000, 180);

                LatLngBounds bounds = LatLngBounds.builder()
                        .include(northSide)
                        .include(southSide)
                        .build();

                place_location.setBoundsBias(bounds);
                place_location.setFilter(typeFilter);

                place_destination.setBoundsBias(bounds);
                place_location.setFilter(typeFilter);

                driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
                driversAvailable.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        LoadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude()));
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

                final double latitude = Common.mLastLocation.getLatitude();
                final double longitude = Common.mLastLocation.getLongitude();


                LoadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude()));

                Log.d("EDMTDEV", String.format("Your location was changed: %f / %f", latitude, longitude));
            } else {
                Log.d("ERROR", "Cannot get your location");
            }
        }
    });
}

private void LoadAllAvailableDriver(final LatLng location) {
    //Add Marker

    mMap.clear();
    mUserMarker = mMap.addMarker(new MarkerOptions()
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
            .position(location)
            .title("You'r Location"));

    //Move Camera to this position
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location, 15.0f));


    //Load all available Driver in distance 3km

    DatabaseReference driverLocation = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
    GeoFire gf = new GeoFire(driverLocation);

    GeoQuery geoQuery = gf.queryAtLocation(new GeoLocation(location.latitude, location.longitude), distance);
    geoQuery.removeAllListeners();

    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
        @Override
        public void onKeyEntered(String key, final GeoLocation location) {
            FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1)
                    .child(key)
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            Rider rider = dataSnapshot.getValue(Rider.class);

                            //Add Driver to map
                            mMap.addMarker(new MarkerOptions()
                                    .position(new LatLng(location.latitude, location.longitude))
                                    .flat(true)
                                    .title(rider.getName())
                                    .snippet("Phone : "+rider.getPhone())
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

        }

        @Override
        public void onKeyExited(String key) {

        }

        @Override
        public void onKeyMoved(String key, GeoLocation location) {

        }

        @Override
        public void onGeoQueryReady() {
            if (distance <= LIMIT) // distance just find for 3 km
            {
                distance++;
                LoadAllAvailableDriver(location);
            }

        }

        @Override
        public void onGeoQueryError(DatabaseError error) {

        }
    });
}

private void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FATEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_signOut) {
        signout();
    } else if (id == R.id.nav_updateInformation) {
        showUpdateInformationDialog();
    }
    return true;

}

private void showUpdateInformationDialog() {
    AlertDialog.Builder alertdialog = new AlertDialog.Builder(Home.this);
    alertdialog.setTitle("Update Information");
    alertdialog.setMessage("Please Enter Your New data");

    LayoutInflater inflater = this.getLayoutInflater();
    View update_info_layout = inflater.inflate(R.layout.layout_update_information, null);

    final MaterialEditText edtName = update_info_layout.findViewById(R.id.edtName);
    final MaterialEditText edtPhone = update_info_layout.findViewById(R.id.edtPhone);
    final ImageView imgAvatar = update_info_layout.findViewById(R.id.imgAvatar);

    alertdialog.setView(update_info_layout);

    imgAvatar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chooseImageAndUpload();
        }
    });

    alertdialog.setView(update_info_layout);

    //set Button
    alertdialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();

            final android.app.AlertDialog waitingDialog = new SpotsDialog(Home.this);
            waitingDialog.show();

            String name = edtName.getText().toString();
            String phone = edtPhone.getText().toString();

            Map<String, Object> update = new HashMap<>();
            if (!TextUtils.isEmpty(name))
                update.put("name", name);
            if (!TextUtils.isEmpty(phone))
                update.put("phone", phone);

            //update
            DatabaseReference riderInformation = FirebaseDatabase.getInstance().getReference(Common.user_rider_tb1);
            riderInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                    .updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    waitingDialog.dismiss();
                    if (task.isSuccessful())
                        Toast.makeText(Home.this, "Information Updated", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(Home.this, "Information Not Update", Toast.LENGTH_SHORT).show();
                }
            });

        }
    });

    alertdialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();

        }
    });

    //show Dialog
    alertdialog.show();


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Common.PICK_IMAGE_RECUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri saveUri = data.getData();
        if (saveUri != null) {
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Uploading...");
            progressDialog.show();

            String imageName = UUID.randomUUID().toString();
            final StorageReference imageFolder = storageReference.child("images/" + imageName);
            imageFolder.putFile(saveUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            progressDialog.dismiss();

                            imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Map<String, Object> update = new HashMap<>();

                                    update.put("avatarUrl", uri.toString());

                                    DatabaseReference riderInformation = FirebaseDatabase.getInstance().getReference(Common.user_rider_tb1);
                                    riderInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                            .updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (task.isSuccessful())
                                                Toast.makeText(Home.this, "Avatar Was Upoload", Toast.LENGTH_SHORT).show();
                                            else
                                                Toast.makeText(Home.this, "Avatar Not Update", Toast.LENGTH_SHORT).show();
                                        }
                                    })
                                            .addOnFailureListener(new OnFailureListener() {
                                                @Override
                                                public void onFailure(@NonNull Exception e) {
                                                    Toast.makeText(Home.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            });


                                }
                            });
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                            progressDialog.setMessage("Uploaded" + progress + "%");
                        }
                    });
        }
    }
}

private void chooseImageAndUpload() {
    //start intent to chose image
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), Common.PICK_IMAGE_RECUEST);


}



@Override
public void onMapReady(GoogleMap googleMap) {

    try {
        boolean isSuccess = googleMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(this, R.raw.uber_style_map)
        );

        if (!isSuccess)
            Log.e("ERROR", "Map Style Load Failed !!!");
    } catch (Resources.NotFoundException ex) {
        ex.printStackTrace();
    }

    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setZoomGesturesEnabled(true);
    mMap.setInfoWindowAdapter(new CustomInfoWindow(this));

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

            if (markerDestination != null)
                markerDestination.remove();
            markerDestination = mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
                    .position(latLng)
                    .title("Destination"));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));

            BottomSheetRiderFragment mBottomsheet = BottomSheetRiderFragment.newInstance(String.format("%f,%f", mLastLocation.getLatitude(), mLastLocation.getLongitude())
            );
            mBottomsheet.show(getSupportFragmentManager(), mBottomsheet.getTag());

        }
    });

    if (ActivityCompat.checkSelfPermission(Home.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(Home.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
      return;
    }
    fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}

}

1 个答案:

答案 0 :(得分:0)

解决方案就是这样

sendRequestToDriver(String driverId)

更改:

此:Token token = postSnapShot.getValue(Token.class);

为此:Token token = new Token(postSnapShot.getValue(String.class));