I'm getting the following error (below), and i have tried a lot of things like change the local to call the method localizacao.setId(usuario.recuperarId()), later tried to instanciety the class usuario alone and not this not solved, this is giving me a hard work to solve, if someone can help i'll be grateful
//////////////////////////////////////////////////////////////////////////////////////////////////
The error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.znovations.citty, PID: 4666
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(DatabaseReference.java:96)
at com.znovations.citty.model.Usuario.recuperarId(Usuario.java:34)
at com.znovations.citty.activitys.MapsActivity.onMapReady(MapsActivity.java:84)
at com.google.android.gms.maps.zzat.zzb(com.google.android.gms:play-services-maps@@18.0.0:1)
at com.google.android.gms.maps.internal.zzaq.zza(com.google.android.gms:play-services-maps@@18.0.0:5)
at com.google.android.gms.internal.maps.zzb.onTransact(com.google.android.gms:play-services-maps@@18.0.0:3)
at android.os.Binder.transact(Binder.java:1043)
at dy.aZ(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (150700-0):2)
at com.google.maps.api.android.lib6.impl.bk.run(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (150700-0):1)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
MapsActivity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private ActivityMapaBinding binding;
private FirebaseAuth autenticacao;
private Toolbar toolbar;
private LocationManager locationManager;
private LocationListener locationListener;
private LatLng localizacaoAtual;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapaBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
toolbar = findViewById(R.id.toolbar);
//Configuracoes inciais
autenticacao = FirebaseAuth.getInstance();
configurarToolbar();
// 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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Recuperar localização do usuário
recuperarLocalizacaoUsuario();
localizacao.setId(usuario.recuperarId());
localizacao.salvarLocalizacao();
}
public void clicarMapa(){
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng latLng) {
mMap.addMarker(
new MarkerOptions()
.position(latLng)
.title("Local de experiencia")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.cranio))
);
}
});
}
Usuario usuario = new Usuario();
UsuarioLocalizacao localizacao = new UsuarioLocalizacao();
private void recuperarLocalizacaoUsuario() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
localizacaoAtual = new LatLng(latitude, longitude);
localizacao.setLatitude(String.valueOf(localizacaoAtual.latitude));
localizacao.setLongitude(String.valueOf(localizacaoAtual.longitude));
clicarMapa();
mMap.clear();
mMap.addMarker(
new MarkerOptions()
.position(localizacaoAtual)
.title("Meu local")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.usuario))
);
mMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(localizacaoAtual, 15)
);
}
};
//Solicitar atualizações de localização
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
10000,
10,
locationListener
);
}
}
public void configurarToolbar(){
toolbar.setTitle("Encontrar");
toolbar.inflateMenu(R.menu.menu_main);
Menu menu = toolbar.getMenu();
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.menuSair:
autenticacao.signOut();
finish();
break;
}
return false;
}
});
}
public void deslogarUsuario(){
autenticacao.signOut();
finish();
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.menuSair:
autenticacao.signOut();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
UsuarioLocalizacao class
public class UsuarioLocalizacao {
private String id;
private String latitude;
private String longitude;
public UsuarioLocalizacao() {
}
public void salvarLocalizacao(){
DatabaseReference firebaseRef = ConfiguracaoFirebase.getFirebaseDatabase();
DatabaseReference user = firebaseRef.child(String.valueOf("Localizacao")).child(getId());
user.setValue(this);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
Usuario class
public class Usuario {
private String id;
private String nome;
private String Email;
private String senha;
private String idSalvo;
public Usuario() {
}
public void salvar(){
DatabaseReference firebaseRef = ConfiguracaoFirebase.getFirebaseDatabase();
DatabaseReference user = firebaseRef.child("usuarios").child( getId());
user.setValue(this);
}
public String recuperarId(){
DatabaseReference referencia = ConfiguracaoFirebase.getFirebaseDatabase();
referencia.child("usuarios")
.child(getId()).get()
.addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if(task.isSuccessful()){
idSalvo = String.valueOf(task.getResult().getValue());
}
}
});
return idSalvo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
@Exclude
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
}
CodePudding user response:
The error comes from this method:
public String recuperarId(){
DatabaseReference referencia = ConfiguracaoFirebase.getFirebaseDatabase();
referencia.child("usuarios")
.child(getId()).get()
.addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if(task.isSuccessful()){
idSalvo = String.valueOf(task.getResult().getValue());
}
}
});
return idSalvo;
}
Since there's only one call to child()
where pass a variable, it's clear that getId()
is returning null
, which is not allowed. You'll want to investigate why id
is null.
Separate from that: this method is gonna return the old value of idSalvo
, since by the time return idSalvo
runs the onComplete
hasn't been called yet. Run your code in a debugger, or add some logging lines, to most easily see this.
For more on this, read: