获取错误 Can't pass null for argument 'pathString' in child()
Getting the error Can't pass null for argument 'pathString' in child()
我收到以下错误(如下),我尝试了很多方法,例如更改本地以调用方法 localizacao.setId(usuario.recuperarId()),后来尝试instanciety class usuario 单独而不是这个没有解决,这让我很难解决,如果有人可以帮助我将不胜感激
////////////////////////////////////////// //////////////////////////////////////////////// ///
错误
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@214515084@21.45.15 (150700-0):2)
at com.google.maps.api.android.lib6.impl.bk.run(:com.google.android.gms.dynamite_mapsdynamite@214515084@21.45.15 (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;
}
}
乌苏里奥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;
}
}
错误来自此方法:
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;
}
因为只有一次调用 child()
传递变量,很明显 getId()
是 returning null
,这是不允许的。您需要调查为什么 id
为空。
与此不同:此方法将 return idSalvo
的旧值,因为在 return idSalvo
运行时 onComplete
尚未被调用. 运行 您在调试器中的代码,或添加一些日志记录行,以便最容易地看到它。
有关这方面的更多信息,请阅读:
我收到以下错误(如下),我尝试了很多方法,例如更改本地以调用方法 localizacao.setId(usuario.recuperarId()),后来尝试instanciety class usuario 单独而不是这个没有解决,这让我很难解决,如果有人可以帮助我将不胜感激
////////////////////////////////////////// //////////////////////////////////////////////// ///
错误
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@214515084@21.45.15 (150700-0):2)
at com.google.maps.api.android.lib6.impl.bk.run(:com.google.android.gms.dynamite_mapsdynamite@214515084@21.45.15 (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;
}
}
乌苏里奥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;
}
}
错误来自此方法:
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;
}
因为只有一次调用 child()
传递变量,很明显 getId()
是 returning null
,这是不允许的。您需要调查为什么 id
为空。
与此不同:此方法将 return idSalvo
的旧值,因为在 return idSalvo
运行时 onComplete
尚未被调用. 运行 您在调试器中的代码,或添加一些日志记录行,以便最容易地看到它。
有关这方面的更多信息,请阅读: