Null object reference in Firebase result loop - java

I want to receive all challenges in Firestore and loop over result to add it to an ArrayList.
db.collection("challenges")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.exists()) {
Log.d(TAG, document.getId() + " => " + document.getData());
Error-> Challenge challenge = document.toObject(Challenge.class);
Log.d(TAG, challenge.getUid() + " => " + challenge.getText());
challengeList.add(document.getData().toString());
}
}
challengeListView.setAdapter(challengeArrayAdapter);
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[])' on a null object reference
Line:
Challenge challenge = document.toObject(Challenge.class);
The log with Log.d(TAG, document.getId() + " => " + document.getData());
is working.
Reference: https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection
This is my my Challenge Class:
public class Challenge {
private Date createdAt;
private Date changedAt;
private String uid;
private String text;
private double longitude;
private double latitude;
public Challenge(String uid, String text, double longitude, double latitude) {
Date currentDate = new Date();
this.createdAt = currentDate;
this.changedAt = currentDate;
this.uid = uid;
this.text = text;
this.longitude = longitude;
this.latitude = latitude; }
public Date getCreatedAt() { return createdAt; }
public Date getChangedAt() { return changedAt; }
public String getUid() { return uid; }
public String getText() { return text; }
public double getLongitude() { return longitude; }
public double getLatitude() { return latitude;}
}

You need to change this line of code:
Challenge challenge = document.toObject(Challenge.class);
with
Map<String, Object> map = task.getResult().getData());
To use toObject() method for a single document, please use the following code:
DocumentReference docRef = db.collection("challenges").document("yourDocument");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Challenge challenge = documentSnapshot.toObject(Challenge.class);
}
});
The error is because of your modell class. Your code looks good. Add the no-argument constructor in your model class. Keep that code or use the Map<String, Object> and your problem will be solved.
To add the no-argument constructor, please add the following line of code in your model class:
public Challenge() {} //Needed for Firebase
after the decalaration of class variables.

I know it is too late but it may help some one in my case my object was
public class RFQ {
public String content,email,receiverKey,productKey,companyKey;
public Sender sender;
public Long createAt;
public RFQ() {
}
public RFQ(String content, String email, String receiverKey, String productKey, String companyKey, Sender sender, Long createAt) {
this.content = content;
this.email = email;
this.receiverKey = receiverKey;
this.productKey = productKey;
this.companyKey = companyKey;
this.sender = sender;
this.createAt = createAt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getCreateAt() {
return createAt;
}
public void setCreateAt(Long createAt) {
this.createAt = createAt;
}
public String getReceiverKey() {
return receiverKey;
}
public void setReceiverKey(String receiverKey) {
this.receiverKey = receiverKey;
}
public String getProductKey() {
return productKey;
}
public void setProductKey(String productKey) {
this.productKey = productKey;
}
public String getCompanyKey() {
return companyKey;
}
public void setCompanyKey(String companyKey) {
this.companyKey = companyKey;
}
public Sender getSender() {
return sender;
}
public void setSender(Sender sender) {
this.sender = sender;
}
}
Everything is proper here but still, I was getting the error that was due to my Sender class in my Sender class I missed to place non-args constructor.

Bro, you need to add Default Constructor in your Challenge Model class as it is needed for Firebase
public Challenge() {} //add this line

Related

How to retrieve array map data and store in array in android studio from firestore? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
i want to retrieve array map from firestore and store it at a array, but it seems like not working at all, any ideas on how to solve it? Thanks...
code example
Firebase database example
Full database structure
Error
DocumentReference docRef = db.collection("user").document("65pH8UOnV4Pz8oxogsqsL9eE91L2");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String[] array = (String[]) document.getData().get("card");
Log.d(TAG, "DocumentSnapshot data: "+ document.getData().get("card"));
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
For parsing the result , you can make model java class which have same structure as on the firestore and then use it to parse in your onComplete method.
//UserResponse.java
public class UserResponse {
private ArrayList<Card> card;
public ArrayList<Card> getCard() {
return card;
}
public void setCard(ArrayList<Card> card) {
this.card = card;
}
public String getBalance() {
return balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
private String balance;
private String email;
private String name;
private String phonenumber;
}
//Card.java
public class Card{
private String cvv;
private String exp;
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getExp() {
return exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getCarddetail() {
return carddetail;
}
public void setCarddetail(String carddetail) {
this.carddetail = carddetail;
}
private String carddetail;
}
And then for in firestore get code change add the following line
UserResponse userResponse = document.toObject(UserResponse.class)
ArrayList<Card> cards = userResponse.getCard();
like this:
DocumentReference docRef = db.collection("user").document("65pH8UOnV4Pz8oxogsqsL9eE91L2");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
UserResponse userResponse = document.toObject(UserResponse.class);
ArrayList<Card> cards = userResponse.getCard();
Log.d(TAG, "DocumentSnapshot data: "+ userResponse.getCard());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});

How to pass raw data in API request using Retrofit2 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to call login API using Retrofit2.
But in onResponse i alwasy get null as response.
Login API endpoint
#FormUrlEncoded
#POST("/api/login/{mobile}")
Call<ResObj> userLogin( #Field("phoneNumber") String mobile );
And the API implementation
private void doLogin(final String mobile){
Call<ResObj> call = userService.login(mobile);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body(); // here i am getting null response.body()
if(resObj.getMessage().equals("true")){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
Toast.makeText(Login.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
ResObj class:
public class ResObj {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I just want to know what causes the error and what are possible solutions.
UPDATE
POSTMAN
You are getting null response in your login API. It may be due to many reasons. You can check your API is working as expected or not using POSTMAN.
And inside your code, you can prevent this type of exception by checking OBJECT is null or not. like the following.
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body();
if(resObj != null){ // checking object is not null
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}else{
// handle null response here.
}
}
Update:
According to your Response JSON, Your Model(ResObj) class should be like the following.
public class ResObj
{
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getDate ()
{
return date;
}
public void setDate (String date)
{
this.date = date;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getContactPerson ()
{
return contactPerson;
}
public void setContactPerson (String contactPerson)
{
this.contactPerson = contactPerson;
}
public String getTimeOut ()
{
return timeOut;
}
public void setTimeOut (String timeOut)
{
this.timeOut = timeOut;
}
public String getProblem ()
{
return problem;
}
public void setProblem (String problem)
{
this.problem = problem;
}
public String getSrNo ()
{
return srNo;
}
public void setSrNo (String srNo)
{
this.srNo = srNo;
}
public String getFieldEngineer ()
{
return fieldEngineer;
}
public void setFieldEngineer (String fieldEngineer)
{
this.fieldEngineer = fieldEngineer;
}
public String getJoNo ()
{
return joNo;
}
public void setJoNo (String joNo)
{
this.joNo = joNo;
}
public String getIrNo ()
{
return irNo;
}
public void setIrNo (String irNo)
{
this.irNo = irNo;
}
public String getDesignation ()
{
return designation;
}
public void setDesignation (String designation)
{
this.designation = designation;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getTimeIn ()
{
return timeIn;
}
public void setTimeIn (String timeIn)
{
this.timeIn = timeIn;
}
public String getProductType ()
{
return productType;
}
public void setProductType (String productType)
{
this.productType = productType;
}
public boolean getStatus ()
{
return status;
}
public void setStatus (boolean status)
{
this.status = status;
}
public String getContactNo ()
{
return contactNo;
}
public void setContactNo (String contactNo)
{
this.contactNo = contactNo;
}
}
You are passing parameter as raw data(according to your screen-shot). So your API endpoint would be like below.
#Headers("Content-Type: application/json")
#POST("/api/login")
Call<ResObj> userLogin(#Body JsonObject jsonObject);
And call your API like this
private void doLogin(final String mobile){
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
Call<ResObj> call = userService.login(paramObject);
call.enqueue(new Callback<ResObj>() {
//your rest of code
});
}
UPDATE-2:
To send object from one Activity to another using intent you have to make your model class Percelable. like this
// implements Parcelable
public class ResObj implements Parcelable {
// ...........your previous code here
// just simply add the following methods
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(date);
dest.writeString(address);
dest.writeString(accountName);
dest.writeString(contactPerson);
dest.writeString(timeOut);
dest.writeString(problem);
dest.writeString(srNo);
dest.writeString(fieldEngineer);
dest.writeString(joNo);
dest.writeString(irNo);
dest.writeString(designation);
dest.writeString(email);
dest.writeString(timeIn);
dest.writeString(productType);
dest.writeByte((byte) (status ? 1 : 0));
dest.writeString(contactNo);
}
public static final Parcelable.Creator<ResObj> CREATOR
= new Parcelable.Creator<ResObj>() {
public ResObj createFromParcel(Parcel in) {
return new ResObj(in);
}
public ResObj[] newArray(int size) {
return new ResObj[size];
}
};
protected ResObj(Parcel in) {
date = in.readString();
address = in.readString();
accountName = in.readString();
contactPerson = in.readString();
timeOut = in.readString();
problem = in.readString();
srNo = in.readString();
fieldEngineer = in.readString();
joNo = in.readString();
irNo = in.readString();
designation = in.readString();
email = in.readString();
timeIn = in.readString();
productType = in.readString();
status = in.readByte() != 0;
contactNo = in.readString();
}
}
Now pass your object via intent like the following.
if(resObj != null){
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("your_key", resObj); // pass resObj and use same key to get data
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
Get data from your ListActivity like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final ResObj yourObject = getIntent().getParcelableExtra("your_key"); // make sure you use same key like data.
// Now you can use your data like that
yourEditText.setText(yourObject.getEmail());
}

Can't convert object of type java.lang.String to type com.example.ezcompras.model.Lojas

I am trying to get a child values, I already get some values in another activities and I had no problem. Now I create a new listener in my new activity and I don't get values. I can find but I can't pass to my object; I will put some code to try explain what I'm saying.
I whant this in red(Edited)
(https://cdn.discordapp.com/attachments/375765058992603136/630091075226173479/unknown.png)
Error
(https://cdn.discordapp.com/attachments/375765058992603136/628991006217469953/unknown.png)
I'm saving values on object (this is my register activity)
private void salvarComerciantePt2() { //save store object
if (dados != null && localizacao != null) {
String categoria = spinnerCategoria.getSelectedItem().toString();//geting a category
if(categoria != null){
empresa.setNomeProprietario((String) dados.get("nomeProprietario"));
empresa.setTelefone((String) dados.get("telefone"));
empresa.setEmail((String) dados.get("email"));
empresa.setCpf((String) dados.get("cpf"));
empresa.setCnpj((String) dados.get("cnpj"));
empresa.setSenha((String) dados.get("senha"));
empresa.setLocalizacao(localizacao);
empresa.setCategoria(categoria);
empresa.setNomeEmpresa(inputNomeEmpresa.getText().toString());
criaUsuarioFirebase(empresa.getEmail(), empresa.getSenha());// create firebase user
}
}
}
Here I'm trying to get values from firebase (I want to get child localizacao)
Debug after this, my code crashes
(https://cdn.discordapp.com/attachments/375765058992603136/629010455473684493/unknown.png)
private void recuperarLocalizacao(){
DatabaseReference lojaRef = mDatabase
.child("empresa")
.child(idLoja) //idStore
.child("localizacao");
lojaRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
local = ds.getValue(Localizacao.class); // try to pass values to my Localizacao.java
}
// Double latitude = local.getLatitude();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Here I'm saving values on Localizacao.java (this is my register activity)
private void autoComplete() {
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i("PlaceCerto", "Place: " + place.getName() + ", " + place.getId());
Geocoder geocoder = new Geocoder(CadastroPt2Activity.this, Locale.getDefault());
try {
List<Address> listaEnderecos = geocoder.getFromLocationName(place.getName(), 1);
if(listaEnderecos != null && listaEnderecos.size() >0){
Address address = listaEnderecos.get(0);
localizacao.setLatitude(place.getLatLng().latitude); // save latitude
localizacao.setLongitude(place.getLatLng().longitude); // save longitude
salvaLocal(address);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceErrado", "An error occurred: " + status);
}
});
}
private void salvaLocal(Address address){// save place
localizacao.setEstado(address.getAdminArea());
localizacao.setCidade(address.getCountryName());
localizacao.setCep(address.getPostalCode());
localizacao.setBairro(address.getSubLocality());
localizacao.setRua(address.getThoroughfare());
localizacao.setNumero(address.getFeatureName());
}
Localizacao.java
package com.example.ezcompras.model;
public class Localizacao {
private String estado;
private String cidade;
private String bairro;
private String rua;
private String numero;
private String cep;
private Double latitude;
private Double longitude;
public Localizacao() {
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
this.rua = rua;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
Create user on firebase (this is my register actitivy)
private void criaUsuarioFirebase (String email, String senha){
mAuth.createUserWithEmailAndPassword(email, senha)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
//Log.d("TagCerta", "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
empresa.salvar(); //writing values
Intent inicio = new Intent(CadastroPt2Activity.this, NavegationActivity.class);
String categoria = spinnerCategoria.getSelectedItem().toString();
inicio.putExtra("categoria", categoria);
startActivity(inicio);
finish();
} else {
// If sign in fails, display a message to the user.
Log.w("TagErrada", "createUserWithEmail:failure", task.getException());
Toast.makeText(CadastroPt2Activity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
this is my store.java where i save all values.
public class Empresa {
private String uid;
private String nomeEmpresa;
private String nomeProprietario;
private String telefone;
private String email;
private String categoria;
private String descricao;
private String idUsuario;
private String senha;
private String tempo;
private String taxa;
private String cpf;
private String cnpj;
private Double precoEntrega;
private Localizacao localizacao;
private String urlImagem;
public Empresa() {
}
public void salvar(){
setUid(UsuarioFirebase.getUsuarioAtual().getUid());
DatabaseReference database = ConfiguracaoFirebase.getFirebaseDatabase();
DatabaseReference reference;
if(getCpf().equals("") || getCpf().equals(null)) {
setCpf(null);
reference = database.child("empresa").child(getUid());
}
else{
reference = database.child("empresa").child(getUid());
}
reference.setValue(this);
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public Localizacao getLocalizacao() {
return localizacao;
}
public void setLocalizacao(Localizacao localizacao) {
this.localizacao = localizacao;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(){
this.descricao =descricao;
}
public String getTaxa(){
return taxa;
}
public void setTaxa(){
this.taxa = taxa;
}
public String getTempo(){
return tempo;
}
public void setTempo(String tempo){
this.tempo = this.tempo;
}
public String getNomeEmpresa() {
return nomeEmpresa;
}
public void setNomeEmpresa(String nomeEmpresa) {
this.nomeEmpresa = nomeEmpresa;
}
public String getNomeProprietario() {
return nomeProprietario;
}
public void setNomeProprietario(String nomeProprietario) {
this.nomeProprietario = nomeProprietario;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Exclude
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getCnpj() {
return cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
public String getUrlImagem() {
return urlImagem;
}
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public Double getPrecoEntrega() {
return precoEntrega;
}
public void setPrecoEntrega(Double precoEntrega) {
this.precoEntrega = precoEntrega;
}
public void setUrlImagem(String urlImagem) {
this.urlImagem = urlImagem;
}
}
this is my json *Edited
"empresa" : {
"7tQGfB7utBWZBtJM2XvuxMH57Sl1" : {
"categoria" : "petshop",
"cnpj" : "",
"cpf" : "99999999999",
"email" : "mauro#gmail.com",
"localizacao" : {
"bairro" : "Jardim Planalto de Viracopos",
"cep" : "13056-016",
"cidade" : "Brazil",
"estado" : "São Paulo",
"latitude" : -22.989735,
"longitude" : -47.1418681,
"numero" : "27",
"rua" : "Rua Luzia Evangelista Eusébio"
},
"nomeEmpresa" : "mauro pet",
"nomeProprietario" : "mauro",
"pedidos" : {
"-Lq7o5ykWNyGBcab6WkZ" : {
"estado" : "Aguardando interação",
"idPedido" : "-Lq7o5ykWNyGBcab6WkZ",
"produto" : {
"descricao" : "teste",
"idProduto" : "-Lq7o5ykWNyGBcab6WkZ",
"idUsuario" : "7tQGfB7utBWZBtJM2XvuxMH57Sl1",
"nome" : "teste",
"preco" : 10
},
"quantidade" : 1
}
},
"telefone" : "+5519982674837",
"uid" : "7tQGfB7utBWZBtJM2XvuxMH57Sl1"
},
You are getting the following error:
Can't convert object of type java.lang.String to type com.example.ezcompras.model.Lojas
Due the fact that you are using the following reference:
DatabaseReference lojaRef = mDatabase
.child("empresa")
.child(idLoja) //idStore
.child("localizacao");
That points to a node that represents a it self a Localizacao object. Because you are looping through its children which are actually strings, you get that error. So if you want to get a single Localizacao object, there is no need to loop, you just can simply get the Localizacao object like this:
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Localizacao localizacao = dataSnapshot.getValue(Localizacao.class);
Log.d(TAG, localizacao.getCidade());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
lojaRef.addListenerForSingleValueEvent(valueEventListener);
And the result in the logcat will be:
Brazil

Failed to convert value of type java.lang.Double to String

I have tried many solutions this code worked for me in the morning and again when i am running it now it is showing an unknown error here is my user class
and I have even tried converting it into doubl also didnt work anyone please help me.
public class createuser {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getIssharing() {
return issharing;
}
public void setIssharing(String issharing) {
this.issharing = issharing;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public createuser() {
}
public String name, email, password, code, issharing, lat, lng,
imgurl, userid;
public createuser(String name, String email, String password, String
code, String issharing, String lat, String lng, String imgurl, String
userid) {
this.name = name;
this.email = email;
this.password = password;
this.code = code;
this.issharing = issharing;
this.lat = lat;
this.lng = lng;
this.imgurl = imgurl;
this.userid = userid;
}
}
here is my runtime class
code = (EditText)findViewById(R.id.editText);
submit = (Button)findViewById(R.id.button);
firebaseDatabase = FirebaseDatabase.getInstance();
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
reference =
firebaseDatabase.getInstance().getReference().child("users");
currentreference =
firebaseDatabase.getInstance().getReference().child("users")
.child(user.getUid());
current_user_id = user.getUid();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query =
reference.orderByChild("code").equalTo(code.getText().toString());
query.addListenerForSingleValueEvent
(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot
dataSnapshot) {
if (dataSnapshot.exists())
{
createuser createuser = null;
for (DataSnapshot childDss :
dataSnapshot.getChildren())
{
createuser =
childDss.getValue(createuser.class);
join_user_id = createuser.userid;
circlereference =
firebaseDatabase.getInstance().getReference().child("users")
.child(join_user_id).child("Circlemembers");
circlejoin circlejoin = new
circlejoin(current_user_id);
circlejoin circlejoin1 = new
circlejoin(join_user_id);
circlereference.child(user.getUid()).setValue(circlejoin)
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull
Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(getApplicationContext(),"user joined
circle",Toast.LENGTH_SHORT).show();
startActivity(new
Intent(joincircle.this,userlocation.class));
}
}
});
}
}
else
{
Toast.makeText(getApplicationContext(),"circle
code is invalid",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError
databaseError) {
}
});
}
});
}
Realtime database is like this
users
NwKzgM0NhuY7gT7eFiN9nwzumMG2
code: "7260232"
email: "trackit385#gmail.com"
imgurl: "na"
issharing: "false"
lat: 17.3932339
lng: 78.4440638
name: "tejesh"
password: "kinglion"
userid: "NwKzgM0NhuY7gT7eFiN9nwzumMG2"
anyone please help me i am not able to resolve it my error is
com.google.firebase.database.DatabaseException: Failed to convert
value of type java.lang.Double to String
You get the following error:
com.google.firebase.database.DatabaseException: Failed to convert
value of type java.lang.Double to String
Because your lat and lng fields in your createuser class are of type String while in your database both fileds hold a double value and this is not correct. To solve this, simply change the type of your fields in your class to double.
public class createuser {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getIssharing() {
return issharing;
}
public void setIssharing(String issharing) {
this.issharing = issharing;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public createuser() {
}
public String name, email, password, code, issharing,
imgurl, userid;
public double lat, lng;
public createuser(String name, String email, String password, String
code, String issharing, double lat, double lng, String imgurl, String
userid) {
this.name = name;
this.email = email;
this.password = password;
this.code = code;
this.issharing = issharing;
this.lat = lat;
this.lng = lng;
this.imgurl = imgurl;
this.userid = userid;
}
}
I don't know, but this class lacks all of it's field declarations. That should be Double lat, Double lng. When the field is String and the setter method sets double, this cannot work, at least not unless adding a matching setter. Also Double and double is not the same data-type. You're confusing primitive with complex data-types (on here they also have two different shades of blue) and also defining setters, but not using them in the constructor ...of which second may be a matter of taste, but first is syntactically wrong, because it means: call by value vs. call by reference. The class probably should be simply called User, because you might end up using it throughout the application.
public class User {
private Double lat;
private Double lng;
...
public User() {}
public User(String name, String email, String password, String code, String issharing, Double lat, Double lng, String imgurl, String userid) {
...
}
...
public Double getLat() { return this.lat; }
public Double getLng() { return this.lng; }
public void setLat(Double value) { this.lat = value; }
public void setLng(Double value) { this.lng = value; }
}

Firebase retrieve stored ArrayList from DataSnapShot gives NullPointerException

My firebase database looks likes this
The blue rectangle is the data I want to retrieve.
Modal class for the blue rectangle looks like this
public class TripToCompany implements Serializable {
String tripDate;
String companyName;
String vehicleNo;
boolean isFinished;
String firstPickUp;
String inTime;
ArrayList<EmpToCompany> emptoCompanyList;
public TripToCompany() {
}
public TripToCompany(String tripDate, String companyName, String vehicleNo, boolean isFinished, String firstPickUp, String inTime, ArrayList<EmpToCompany> emptoCompanyList) {
this.tripDate = tripDate;
this.companyName = companyName;
this.vehicleNo = vehicleNo;
this.isFinished = isFinished;
this.firstPickUp = firstPickUp;
this.inTime = inTime;
this.emptoCompanyList = emptoCompanyList;
}
public TripToCompany(String tripDate, String companyName, String vehicleNo) {
this.tripDate = tripDate;
this.companyName = companyName;
this.vehicleNo = vehicleNo;
this.isFinished = false;
this.inTime = "-";
this.emptoCompanyList = new ArrayList<>();
}
public String getTripDate() {
return tripDate;
}
public void setTripDate(String tripDate) {
this.tripDate = tripDate;
}
public String getCompany() {
return companyName;
}
public void setCompany(String companyName) {
this.companyName = companyName;
}
public String getVehicleNo() {
return vehicleNo;
}
public void setVehicleNo(String vehicleNo) {
this.vehicleNo = vehicleNo;
}
public boolean isFinished() {
return isFinished;
}
public void setFinished(boolean isFinished) {
this.isFinished = isFinished;
}
public String getFirstPickUp() {
return firstPickUp;
}
public void setFirstPickUp(String firstPickUp) {
this.firstPickUp = firstPickUp;
}
public String getInTime() {
return inTime;
}
public void setInTime(String inTime) {
this.inTime = inTime;
}
public ArrayList<EmpToCompany> getEmptoCompanyList() {
return emptoCompanyList;
}
public void setEmptoCompanyList(ArrayList<EmpToCompany> emptoCompanyList) {
emptoCompanyList = emptoCompanyList;
}
public void addEmpToCompanyList(EmpToCompany etc) {
if (emptoCompanyList.size() == 0) {
firstPickUp = etc.getCabInTime();
}
emptoCompanyList.add(etc);
}
}
I am fetching the data from firebase using the standard query. Here is the code
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance();
DatabaseReference mRef = defaultDatabase.getReference("data");
Query query = mRef.child("toComp/" + companyId + "/" + fromDate + "/" + shiftTimeId + "/");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot ds) {
if (ds.exists()) {
System.out.println("exist");
for (DataSnapshot singleSnapshot : ds.getChildren()) {
TripToCompany trpObj = (TripToCompany) singleSnapshot.getValue(TripToCompany.class);
ArrayList<EmpToCompany>ee= trpObj.getEmptoCompanyList();
System.out.println("Company Name: "+trpObj.getCompany()); //successfully retrived
System.out.println("Employee Count: " + ee.size()); //unable to fetch it. Gives NullPointerException
}
} else {
System.out.println("error");
}
}
#Override
public void onCancelled(DatabaseError de) {}
});
I am able to get the remaining data successfully from firebase. The data in red rectangle is the ArrayList, and I am unable to fetch it(show in red rectangle in the image). I have printed in the console using Sysout and I am unable to get ArrayList data. It returns NullPointerException. How can I fetch that ArrayList in the TripToCompany Object?
To solve this, please change the following lines of code:
public void setEmptoCompanyList(ArrayList<EmpToCompany> emptoCompanyList) {
emptoCompanyList = emptoCompanyList;
}
to
public void setEmptoCompanyList(ArrayList<EmpToCompany> emptoCompanyList) {
this.emptoCompanyList = emptoCompanyList;
// ^
}
You should assign the value of the local emptoCompanyList variable to the member class (this) field, not to the same variable.
In your JSON case from the picture I see, you need to change this code:
ArrayList< EmpToCompany> emptoCompanyList;
to:
ArrayList< String> emptoCompanyList;
But if you want arraylist of EmpToCompany class, you need to show what you have inside the red rectangle for the keys 0 and 1 .... and I will help you :)

Categories

Resources