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 :)
Related
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());
}
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
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
I'm new in using Firebase and Android. I have a project to save an order and a payment in one child and show them all in adapter. But it show error when get data with postSnapshot from model class. I dont know where the fault in my project. Error like this:
com.firebase.client.FirebaseException: Failed to bounce to type
and
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "payment"
My firebase structure looks like:
And then this is my java code:
MainActivity.java
String status = "orderSucces";
Firebase ref = new Firebase("https://myfirebase-d8a8a.firebaseio.com/order");
orderID = "-Kxi37Ro2oCPxQkb5L5u";
Query query = ref.child(status).orderByChild("orderID").equalTo(orderID);
query.addValueEventListener(new com.firebase.client.ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
progressBar.setVisibility(View.VISIBLE);
if (dataSnapshot.exists()) {
for (com.firebase.client.DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
OrderModel data = postSnapshot.getValue(OrderModel.class);
orderModel.add(data);
adapter = new Adapter(getApplication(), orderModel);
//adding adapter to recyclerview
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
} else {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
OrderModel.java
public class PemesananModel implements Serializable {
public String orderID, paymentID, buyerName, buyerPhone, paymentMethod;
PemesananModel() {}
public PemesananModel(String orderID, String paymentID, String buyerName, String buyerPhone, String paymentMethod) {
this.orderID = orderID;
this.paymentID = paymentID;
this.buyerName = buyerName;
this.buyerPhone = buyerPhone;
this.paymentMethod = paymentMethod;
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getPaymentID() {
return paymentID;
}
public void setPaymentID(String paymentID) {
this.paymentID = paymentID;
}
public String getBuyerName() {
return buyerName;
}
public void setBuyerName(String buyerName) {
this.buyerName = buyerName;
}
public String getBuyerPhone() {
return buyerPhone;
}
public void setBuyerPhone(String buyerPhone) {
this.buyerPhone = buyerPhone;
}
public String getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(String paymentMethod) {
this.paymentMethod = paymentMethod;
}
}
Since your JSON doesn't have a property called payment, it seems like you're simply reading the data at the wrong level in your JSON tree.
The solution is to attach your listener on the correct level in the tree, like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference paymentRef = rootRef
.child("order")
.child("orderSucces")
.child(orderID)
.child("payment");
This is the structure of my Realm database:
public class ARDatabase extends RealmObject
{
#PrimaryKey
private String uid;
private String namex;
private String desc;
private boolean isVideo;
private boolean isDeleted;
private String urlImg;
private String urlApp;
private int updates;
private boolean isDownloaded;
private String location;
public ARDatabase(){}
public String getUid()
{
return uid;
}
public void setUid(String uid)
{
this.uid = uid;
}
public String getNamex()
{
return namex;
}
public void setNamex(String namex)
{
this.namex = namex;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc)
{
this.desc = desc;
}
public boolean getIsVideo()
{
return isVideo;
}
public void setIsVideo(boolean isVideo)
{
this.isVideo = isVideo;
}
public boolean getIsDeleted()
{
return isDeleted;
}
public void setIsDeleted(boolean isDeleted)
{
this.isDeleted = isDeleted;
}
public String getUrlImg()
{
return urlImg;
}
public void setUrlImg(String urlImg)
{
this.urlImg = urlImg;
}
public String getUrlApp()
{
return urlApp;
}
public void setUrlApp(String urlApp)
{
this.urlApp = urlApp;
}
public int getUpdates()
{
return updates;
}
public void setUpdates(int updates)
{
this.updates = updates;
}
public boolean getIsDownloaded()
{
return isDownloaded;
}
public void setIsDownloaded(boolean isDownloaded)
{
this.isDownloaded = isDownloaded;
}
public String getLocation()
{
return location;
}
public void setLocation(String location)
{
this.location = location;
}
}
And I can successfully add objects to the database.
The problem comes when I need to update an object.
This is what I tried:
private void downloadUpdateDatabase(String uid,String location_address) throws RealmException
{
mRealm.beginTransaction();
ARDatabase db = new ARDatabase();
db.setUid(uid);
db.setIsDownloaded(true);
db.setLocation(location_address);
mRealm.copyToRealmOrUpdate(db);
mRealm.commitTransaction();
Log.e("TAG","DOWNLOAD UPDATE COMPLETED");
}
The problem here is when I invoke this method. The mentioned fields get updated, but the not mentioned fields in this method become null or zero.
Of course I can set values for all fields by invoking their setters, however from where I invoke this method, I can't get all the field values.
So, the Question is: How do I update my realm database in such a way that the existing fields don't become null ?
P.S.:
My Realm version is :0.84.1, compile 'io.realm:realm-android:0.84.1'
the field that are mentioned gets updated, however the fields that are not mentioned in this method becomes null or zero
Well, yes, all fields are their defaults at this point.
ARDatabase db = new ARDatabase();
Have you tried to query for the current record, then update the fields, then put that object back?
In other words, you have String uid, so something like
private void downloadUpdateDatabase(String uid,String location_address) throws RealmException
{
mRealm.beginTransaction();
ARDatabase db = mRealm.where(ARDatabase.class).equalTo("uid", uid).findFirst();
db.setIsDownloaded(true);
db.setLocation(location_address);
mRealm.copyToRealmOrUpdate(db);
mRealm.commitTransaction();
}
Or, probably better in async fashion.
private void downloadUpdateDatabase(final String uid, final String location_address) throws RealmException
{
mRealm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ARDatabase db = realm.where(ARDatabase.class).equalTo("uid", uid).findFirst();
db.setIsDownloaded(true);
db.setLocation(location_address);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
}
Instead of
mRealm.beginTransaction();
ARDatabase db = new ARDatabase();
db.setUid(uid);
db.setIsDownloaded(true);
db.setLocation(location_address);
mRealm.copyToRealmOrUpdate(db);
mRealm.commitTransaction();
Log.e("TAG","DOWNLOAD UPDATE COMPLETED");
There should be
mRealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ARDatabase db = realm.where(ARDatabase.class).equalTo("uid", uid).findFirst();
if(db == null) {
db = realm.createObject(ARDatabase.class, uid);
}
db.setIsDownloaded(true);
db.setLocation(location_address);
}
});
Log.e("TAG","DOWNLOAD UPDATE COMPLETED");