调用(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));
}
}
答案 0 :(得分:1)
首先,您没有在任何地方调用getUserData()
方法。我了解到您也尝试在onCreate()
中添加该逻辑,但这没有用。
添加侦听器并不意味着您可以立即获得期望的效果。
仅使用onMapReady()
方法设置地图,其设置不依赖于User
。仅当您检测到User
数据中的更改时,才添加/修改地图标记。查看更改:
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);
LatLng userL = new LatLng(user.getLat(),user.getLng());
if(mMap!=null){
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userL).title("Your
Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userL,17));
}
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;
}
请调用方法getUserData()
或将其代码移至onCreate()
。