调用 (user.getlat) 和 (user.getlng) 时出现问题。我已经全局声明了用户对象,并在 getUserData() 方法中对其进行了初始化。
但是当我运行应用程序时,应用程序崩溃并且在 logcat 中说:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“double com.example.profile.User.getLat()”
public class Profile extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager locationManager;
private LocationListener locationListener;
private FirebaseAuth mAuth;
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference myRef = database.child("users");
User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
mAuth = FirebaseAuth.getInstance();
}
public void getUserData(){
String uID = mAuth.getCurrentUser().getUid();
myRef.child(uID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getChildren();
user = dataSnapshot.getValue(User.class);
Toast.makeText(Profile.this, "" + user.lng, Toast.LENGTH_LONG).show(); // Prints the value normally!
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Profile.this, "Failed to read from database!", Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng userL = new LatLng(user.getLat(),user.getLng()); // The problem occurs here!
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userL).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userL,17));
}
}
神不在的星期二
相关分类