Android Firebase pass data iterate map - java

I want to pass data from first activity to second activity. But when I want to read the data in the second activity response is null. How can I solve this problem?
Firebase Node
Pro_:
Basket:
ID_1:
cat: “Tech”
info:”iOS”
orderid:”Ref_1”
ID_2:
cat: “Tech”
info:”Android”
orderid:”Ref_2”
name:”Mike”
My struct
public class Name_Struct implements Serializable {
private String name;
private Map<String, Object> basket;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#PropertyName("Basket")
public Map<String, Object> getBasket() {
return basket;
}
public void setBasket(Map<String, Object> basket) {
this.basket = basket;
}
}
First Activity
private void retrieve_data(){
Query query = FirebaseDatabase.getInstance().getReference()
.child(“Pro_”);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
mName.clear();
for(DataSnapshot snp : snapshot.getChildren()){
Name_Struct names = snp.getValue(Name_Struct.class);
mName.add(names);
}
mName_adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
EDIT_1 First Adapter
final Name_Struct newModel = Name_Struct(position);
Bundle bundle1=new Bundle();
bundle1.putSerializable("basket", (Serializable) newModel.getBasket());
intent.putExtras(bundle1);
EDIT_1 Second Activity
Map <String, Object> map1 = (Map)bundle.getSerializable("basket");
Detail_Struct detail = new Detail_Struct(
map1.get("cat"),map1.get("info"),map1.get("orderid"));
mDetail_Struct.add(detail);
for (Map.Entry<String, Object> entry : map1.entrySet()) {
Log.d("Map_array:"+ map1);
Map_array:{ID_1={cat=Tech, info=iOS, orderid=Ref_1}, D_2={cat=Tech,
info=Android, orderid=Ref_2}}
Log.d("Map_value:"+ entry.getValue());
Map_value:{cat=Tech, info=iOS, orderid=Ref_1} Map_value:{cat=Tech,
info=Android, orderid=Ref_2}
Log.d("Map_object:"+ map1.get("orderid"));
null line???
Map_object:null Map_object:null
}
EDIT_1 Detail Struct
public class Detail_Struct {
private String cat;
private String info;
private String orderid;
public String getCat() {
return cat;
}
public void setCat(String cat) {
this.cat = cat;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}

Related

Android Firebase pass data recyclerview to recyclerview

I want to pass data RC_1 to RC_2. How can I do this(cat, info, orderid) RecyclerView to RecyclerView?Examp.pic_1
My firebase node is like as to picture.
My firebase node
//RC_1 Struct
public class Name_Struct {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//RC_2 Struct
public class Detail_Struct {
private String cat;
private String info;
private String orderid;
public String getCat() {
return cat;
}
public void setCat(String cat) {
this.cat = cat;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
RC_1 for;
//Myactivity_1
private void rc_1_get_name(){
Query query = FirebaseDatabase.getInstance().getReference()
.child(“Pro_”);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
mName.clear();
for(DataSnapshot snp : snapshot.getChildren()){
Name_Struct names = snp.getValue(Name_Struct.class);
for (DataSnapshot recipeSnapshot: snp.child(“basket”).getChildren()) {
mName.add(names);
}
}
mName_adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
RC_1 for;
//Myadapter_ 1
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") int position) {
final Name_Struct names = mName.get(position);
holder.name_.setText(names.getName()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, RC_2.class);
???
mContext.startActivity(intent);
}
}
As I see in your screenshot, the "Pro_" node contains a name that has the value of "Mike". This means that you can map that node into an object of type Name_Struct. And you are doing that successfully. Under the same node, there is however another node called "Basket". That node is represented by a Map object, where the keys are represented by those IDs (ID_1, ID_2, etc) and the value by Detail_Struct objects. To be able to map the data under the "Basket" node, you have to add a new property in your Name_Struct class called basket like this:
public class Name_Struct implements Serializable {
private String name;
private Map<String, Object> basket;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#PropertyName("Basket")
public Map<String, Object> getBasket() {
return basket;
}
public void setBasket(Map<String, Object> basket) {
this.basket = basket;
}
}
Now to pass the data to the second activity, you have to add iterate the Map and create a List<Detail_Struct> that can be added to the Intent so it can be read in the second activity.

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

com.firebase.client.FirebaseException: Failed to bounce to type

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");

Android Firebase Database - not appropriate Object conversion from Database structure

My database structure is like this:
users
8aWcF6GQmpezfJkVnW5uYoJ2wtI3
email: "jack"#mail.com"
height: "180cm"
imgUrl: "https://www.goldennumber.net/wp-content/uploads..."
matches
WEZ36bsEFXQtrJWQJVT3KMtsgQC3: true
8oqmrMVZ57XXlunIAUEeBgKFZ0h2: true
uid: "8aWcF6GQmpezfJkVnW5uYoJ2wtI3"
username: "jack"
I am trying to convert this structure to this object:
public class UserMatchDTO {
private String uid;
private String username;
private String height;
private String imgUrl;
private String email;
private HashMap<String, Boolean> userMatches = new HashMap<>();
public UserMatchDTO() {
}
public UserMatchDTO(String uid, String username, String height, String imgUrl, String email, HashMap<String, Boolean> userMatches) {
this.uid = uid;
this.username = username;
this.height = height;
this.imgUrl = imgUrl;
this.email = email;
this.userMatches = userMatches;
}
public String getUid() {
return uid;
}
public String getUsername() {
return username;
}
public String getHeight() {
return height;
}
public String getImgUrl() {
return imgUrl;
}
public HashMap<String, Boolean> getUserMatches() {
return userMatches;
}
public void setUserMatches(HashMap<String, Boolean> userMatches) {
this.userMatches = userMatches;
}
public String getEmail() {
return email;
}
}
Here is the method where I convert this to my object:
final List<UserMatchDTO> userMatchDTOs = new ArrayList<>();
databaseReference.child("users").addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
userMatchDTOs.add(userMatchDTO);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
However, when I debug this, the userMatches HashMap is always size 0. So why child "matches" from "user" is not converted to HashMap?
Here is what the snapshot looks like:
DataSnapshot { key = 8oqmrMVZ57XXlunIAUEeBgKFZ0h2, value = {email=jack#mail.com, height=180cm, uid=8aWcF6GQmpezfJkVnW5uYoJ2wtI3, imgUrl=https://www.goldennumber.net/wp-content/uploads/2013/08/florence-colgate-england-most-beautiful-face.jpg, username=jack, matches={WEZ36bsEFXQtrJWQJVT3KMtsgQC3=true, 8oqmrMVZ57XXlunIAUEeBgKFZ0h2=true}} }
Ok, so i manage to solve this, but I am not sure if this is good solution.
I just map the response to Object first and then cast this to the HashMap.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
Object object = matchSnapshot.child("matches").getValue();
if(object != null){
userMatchDTO.setUserMatches((HashMap<String, Boolean>) object);
}
userMatchDTOs.add(userMatchDTO);
}
Is any better solution for this?

How to set Retrofit response body data in Listview

In Daata function try to fetch data from server. Successfully fetched, but data cant be set in ArrayList
List<FlowerListModel>flowerListModels=new ArrayList<>();
Cause i want to set flowerListModels data in FlowerAdapter and show in listview
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
List<FlowerListModel>flowerListModels=new ArrayList<>();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
Here is FlowerListModel class
package bdservers.com.schoolmanagement.Model;
public class FlowerListModel {
private String category;
private String instructions;
private String photo;
private String name;
private String price;
public FlowerListModel(){}
public FlowerListModel(String category, String instructions, String photo, String name,String price){
this.category=category;
this.instructions=instructions;
this.photo=photo;
this.name=name;
this.price=price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
You are setting empty ArrayList to your adapter, I have highlighted the line where you have made the error, and also the correct line that you need
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
/**
* You are setting this empty list to adapter
*List<FlowerListModel>flowerListModels=new ArrayList<>();
*/
List<FlowerListModel> flowerListModels = new ArrayList<>();
flowerListModels = response.body();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
You are creating new empty List here: List<FlowerListModel>flowerListModels=new ArrayList<>();
You can try something like this:
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),response.body());
listView.setAdapter(flowerAdapter);
}
Create BaseResponse model like this
public class BaseResponse {
#SerializedName("data")
private List<Object> alObjects;
public BaseResponse(List<Object> alObjects) {
this.alObjects = alObjects;
}
public List<Object> getAlObjects() {
return alObjects;
}
public void setAlObjects(List<Object> alObjects) {
this.alObjects = alObjects;
}
}
Then get data from server
#POST(Constants.URL_API_DATA)
BaseResponse executeBaseResponse(#Body String mData);
Cheers!!

Categories

Resources