This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12个答案)
5个月前关闭。
这是我的ShopsApp,可在其中在地图上创建新标记并将其添加到Firebase。我在将一些有关标记的信息添加到数据库时遇到了麻烦。在日志中,我看到此异常:
com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)'
在空对象引用上
在pl.admindoit.shopsapp.EditActivity $ 1 $ 1.onDataChange(EditActivity.java:79)
这是我的EditActivity:
和MapsActivity:
(12个答案)
5个月前关闭。
这是我的ShopsApp,可在其中在地图上创建新标记并将其添加到Firebase。我在将一些有关标记的信息添加到数据库时遇到了麻烦。在日志中,我看到此异常:
com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)'
在空对象引用上
在pl.admindoit.shopsapp.EditActivity $ 1 $ 1.onDataChange(EditActivity.java:79)
这是我的EditActivity:
public
class EditActivity extends Activity implements View.OnClickListener {
private DatabaseReference mDatabase;
private Button btnsave;
private EditText name;
private EditText describe;
private EditText radius;
private FirebaseAuth mAuth;
GoogleMap mGoogleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
btnsave = (Button)findViewById(R.id.save);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Shops");
name = (EditText)findViewById(R.id.name);
describe = (EditText)findViewById(R.id.describe);
radius = (EditText)findViewById(R.id.radius);
btnsave.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String uId = mUser.getUid();
mDatabase.keepSynced(true);
final LatLng latlng = (LatLng) getIntent().getParcelableExtra("location");
final EditText title = (EditText) findViewById(R.id.name);
btnsave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
if(view == btnsave)
{
saveShopInformation();
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot s : dataSnapshot.getChildren())
{
FirebaseMarker firebaseMarker = s.getValue(FirebaseMarker.class);
mGoogleMap.addMarker(new MarkerOptions()
.title(firebaseMarker.name + " " +
firebaseMarker.description + " " +
firebaseMarker.radius
));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
MarkerOptions marker = new MarkerOptions().position(latlng);
if (title.getText() != null) {
marker.title(title.getText().toString());
}
Intent resultIntent = new Intent();
resultIntent.putExtra("marker", marker);
setResult(Activity.RESULT_OK, resultIntent);
finish();
name.getText().clear();
describe.getText().clear();
radius.getText().clear();
}
});
}
private void saveShopInformation()
{
String mName = name.getText().toString().trim();
String mDescribe = describe.getText().toString().trim();
String mRadius = radius.getText().toString().trim();
FirebaseMarker firebaseMarker = new FirebaseMarker(mName ,mDescribe, mRadius);
mDatabase.child("Shops").setValue(firebaseMarker);
Toast.makeText(this,"Saved",Toast.LENGTH_LONG).show();
}
@Override
public void onClick(View v) {
if(v == btnsave)
{
saveShopInformation();
name.getText().clear();
describe.getText().clear();
radius.getText().clear();
}
} }
和MapsActivity:
public class ShopsActivity extends AppCompatActivity
implements OnMapReadyCallback {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;
private static final int EDIT_REQUEST = 1;
DatabaseReference mUsers;
Marker marker;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shops);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
mapFrag.getMapAsync(this);
mUsers = FirebaseDatabase.getInstance().getReference("Shops");
mUsers.push().setValue(marker);
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String uId = mUser.getUid();
mUsers.keepSynced(true);
}
@Override
public void onPause() {
super.onPause();
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(60000); // one minute interval
mLocationRequest.setFastestInterval(60000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//Request to permission
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
} else {
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
final List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//Last location
Location location = locationList.get(locationList.size() - 1);
Log.i("ShopsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Current marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Intent edit = new Intent(ShopsActivity.this, EditActivity.class);
edit.putExtra("location", latLng);
ShopsActivity.this.startActivityForResult(edit, EDIT_REQUEST);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title((latLng.latitude) + " : " + latLng.longitude);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.addMarker(markerOptions);
}
});
}
};
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(ShopsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
最佳答案
您尚未在EditActivity类中初始化mGoogleMap。您需要先对其进行初始化,然后再调用(mGoogleMap)。
10-08 18:27