how to upload file from retrofit android java - java

am using retrofit for insert data to my webservice, I have made it before but without uploading the image and the insert is successful, the input field through the model class not in interface,how I add an input field fot uploading files through the model so that it can be sent to my web services storage folder?
I have tried but failed please help
for my insert in activity
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tanggal = textdate.getText().toString();
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
Date date1= null;
try {
date1 = formatter1.parse(tanggal);
} catch (ParseException e) {
e.printStackTrace();
}
SwabtestModel sw = new SwabtestModel();
sw.sethasil(texthasil.getText().toString());
sw.settanggal(date1);
sw.settempat(texttempat.getText().toString());
sw.setuserid(Integer.valueOf(txtuserid.getText().toString()));
sw.setFile_name(new File(txturi.getText().toString()));
save(sw);
}
});
public void save(SwabtestModel sw){
Call<SwabtestModel> call = swabtestService.addswab(sw);
call.enqueue(new Callback<SwabtestModel>() {
#Override
public void onResponse(Call<SwabtestModel> call, Response<SwabtestModel> response) {
if(response.isSuccessful()){
String status = response.body().getStatus();
Toast.makeText(SwabtestActivity.this, status, Toast.LENGTH_LONG).show(); }
}
#Override
public void onFailure(Call<SwabtestModel> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
for my file chooser
public void onActivityResult(int request_code, int result_code, Intent data){
super.onActivityResult(request_code,result_code,data);
if(request_code==request_code && result_code== Activity.RESULT_OK){
if(data==null){
return;
}
uri= data.getData();
filePath = uri.getPath();
txturi.setText(filePath);
}
}
public void openfilechooser(){
Intent intent= new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent,request_code);
}
for my model class
public class SwabtestModel {
#SerializedName("hasil")
#Expose
private String hasil;
#SerializedName("tanggal")
#Expose
private Date tanggal;
#SerializedName("tempat")
#Expose
private String tempat;
#SerializedName("file_name")
#Expose
private File file_name;
#SerializedName("user_id")
#Expose
private Integer user_id;
String data;
String status;
public SwabtestModel(String hasil, Date tanggal, String tempat){
this.hasil = hasil;
this.tanggal = tanggal;
this.tempat = tempat;
}
public void sethasil(String hasil) {
this.hasil = hasil;
}
public String gethasil(){
return hasil;
}
public void settanggal(Date tanggal) {
this.tanggal = tanggal;
}
public Date gettanggal(){
return tanggal;
}
public void settempat(String tempat) {
this.tempat = tempat;
}
public String gettempat(){
return tempat;
}
public void setuserid(Integer user_id) {
this.user_id = user_id;
}
public Integer getuserid(){
return user_id;
}
public void setFile_name( File file_name) {
this.file_name =file_name ;
}
public File getfilename(){
return file_name;
}
public String getData() {
return data;
}
public String getStatus() {
return status;
}
}
my interface
public interface swabtestService
{
#GET("hasil-antigen-list")
Call<List<SwabtestModel>> getUsers();
#POST("insert-hantigen")
Call<SwabtestModel> addswab(#Body SwabtestModel swabtest);
}

To upload files you should use Multipart, Please refer to this post for example and please ping me if you have any queries https://stackoverflow.com/a/39953566

Take a data in list like #Part List<MultipartBody.Part> partFile
private List<MultipartBody.Part> getMapPartListSave(List<PojoAttachDocList> fields) {
List<MultipartBody.Part> mapPart = new ArrayList<>();
for (int i = 0; i < fields.size(); i++) {
**PojoAttachDocList** attachDoc = fields.get(i);
if (!attachDoc.isAttached() && attachDoc.getDocFile() != null && attachDoc.getDocFile().exists()
&& attachDoc.getDocFile().length() > 0) {
String fileParam = PARAMS_DOCUMENT + "[" + i + "]";
mapPart.add(MultipartBody.Part.createFormData(fileParam, attachDoc.getDocFile().getName(),
RequestBody.create(MediaType.parse("*/*"), attachDoc.getDocFile())));
}
}
return mapPart;
}
Convert it to MultipartBody

Related

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

Error passing ArrayList<Object> to another activity - Parcelable encountered IOException writing serializable object

I try to pass an ArrayList<DatosVenta> to another Activity but i have this problem: Parcelable encountered IOException writing serializable object (name = com.madmvx.proyectou.Models.ModelUtils.DatosVenta)
My class DatosVenta implements Serializable
i tried with Parcelable but i don't get nothing in the other Activity
i get null
public class DatosVenta implements Serializable {
Vendedor vendedor;
String nombreCliente, gestionRealizada, observaciones, zona, quienAtiende, fecha;
public DatosVenta(Vendedor vendedor, String nombreCliente, String gestionRealizada, String observaciones, String zona, String fecha, String quienAtiende) {
this.vendedor = vendedor;
this.nombreCliente = nombreCliente;
this.gestionRealizada = gestionRealizada;
this.observaciones = observaciones;
this.zona = zona;
this.fecha = fecha;
this.quienAtiende = quienAtiende;
this.zona = zona;
}
public DatosVenta() {
}
public String getQuienAtiende() {
return quienAtiende;
}
public void setQuienAtiende(String quienAtiende) {
this.quienAtiende = quienAtiende;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public Vendedor getVendedor() {
return vendedor;
}
public void setVendedor(Vendedor vendedor) {
this.vendedor = vendedor;
}
public String getNombreCliente() {
return nombreCliente;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
public String getGestionRealizada() {
return gestionRealizada;
}
public void setGestionRealizada(String gestionRealizada) {
this.gestionRealizada = gestionRealizada;
}
public String getObservaciones() {
return observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
public String getZona() {
return zona;
}
public void setZona(String zona) {
this.zona = zona;
}
}
if(!datosVentaList.isEmpty() && datosVentaList != null){
Intent intent = new Intent(getContext(), AdminShowRuterosActivity.class);
intent.putExtra("datosVentaList",datosVentaList);
startActivity(intent);
dismiss();
}else{
Log.d("LISTA<>", "No hay datos");
dismiss();
}
in my AdminShowRuterosActivity.class
datosVentaArrayList = (ArrayList<DatosVenta>)getIntent().getSerializableExtra("datosVentaList");

Firebase push notification send extra data from a model class

I was using FirebaseMessagingService to send a notification to other users using my app, the problem is I cannot add extra data to the message. I have a notification, sender, and data model classes. Problem is when I try adding the data model when sending the token however I get invalid JSON.
Notifcation class:
public String title;
public String body;
public Notification() {
}
public Notification(String title, String body) {
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Sender class:
public class Sender {
public Notification data;
public data extra;
public String to;
public Sender() {
}
public Sender(Notification data, data extra, String to) {
this.data = data;
this.to = to;
this.extra = extra;
}
public Notification getData() {
return data;
}
public void setData(Notification data) {
this.data = data;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
}
data class:
public class data {
public String username;
public data() {
}
public data(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Home:
data extra = new data("Test");
Notification notification = new Notification("title test", "body test");
Sender content = new Sender(notification, extra, token.getToken());
mService.sendMessage(content)
.enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
Log.i(TAG, "onResponse: " + response.toString());
if (response.body().success == 1){
Toast.makeText(c, "Request sent!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c, "Request failed!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
Log.e(TAG, "onFailure: "+ t.getMessage());
}
});
MyFirebaseMessaingService:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().isEmpty()){
} else {
String title = remoteMessage.getData().get("title").toString();
String body = remoteMessage.getData().get("body").toString();
String username = remoteMessage.getData().get("username").toString();
Log.i(TAG, "showNotifcation: " + title + body + username);
}
}
Problem occurs when i send extra data from the model class i.e the username. Without send extra data i.e just the notification it will work fine.

Null object reference in Firebase result loop

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

Categories

Resources