How to retrieve data from database using hashmap? - java

I have this recyclerview, when I click on an item I want to get the data in the red square from database.
And I want to show it like that
This is how I save it :
Save.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v) {
String refernce = TextRef.getEditText().getText().toString();
String nompdv = textNomPdv.getEditText().getText().toString();
String etat = textEtatCommande.getEditText().getText().toString();
String datecommande = TextDateCommande.getEditText().getText().toString();
String produitcommande = textProduit.getEditText().getText().toString();
String qntcommande = editTextProduitQnt.getEditText().getText().toString();
DatabaseReference newPost = reference.child(refernce);
newPost.child("refernce").setValue(refernce);
newPost.child("nompdv").setValue(nompdv);
newPost.child("etat").setValue(etat);
newPost.child("datecommande").setValue(datecommande);
newPost.child("user_id").setValue(uid);
Map<String, Object> values = new HashMap<>();
values.put(produitcommande, qntcommande);
DatabaseReference produitRef = reference.child(refernce).child("produit");
produitRef.updateChildren(values);
This is how I send data from first activity (recyclerview) :
v.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Order_detail.class);
int pos = v.getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
Order clickedDataItem = listArray.get(pos);
intent.putExtra("nompdv", clickedDataItem.getNompdv());
intent.putExtra("reference", clickedDataItem.getRefernce());
intent.putExtra("datecommande", clickedDataItem.getDatecommande());
intent.putExtra("etat", clickedDataItem.getEtat());
}
view.getContext().startActivity(intent);
}
});
How to do to get the products and their quantities when clicking on an item in recyclerview?
Update : This my Order class :
public class Order implements Serializable {
public String refernce, nompdv, etat, datecommande, produitcommande, qntcommande;
String user_id;
public Order(){}
public Order(String refernce, String nompdv, String etat, String datecommande, String produitcommande, String qntcommande, String user_id) {
this.refernce = refernce;
this.nompdv = nompdv;
this.etat = etat;
this.datecommande = datecommande;
this.produitcommande = produitcommande;
this.qntcommande = qntcommande;
this.user_id = user_id;
}
public String getRefernce() {
return refernce;
}
public void setRefernce(String refernce) {
this.refernce = refernce;
}
public String getNompdv() {
return nompdv;
}
public void setNompdv(String nompdv) {
this.nompdv = nompdv;
}
public String getEtat() {
return etat;
}
public void setEtat(String etat) {
this.etat = etat;
}
public String getDatecommande() {
return datecommande;
}
public void setDatecommande(String datecommande) {
this.datecommande = datecommande;
}
public String getProduitcommande() {
return produitcommande;
}
public void setProduitcommande(String produitcommande) {
this.produitcommande = produitcommande;
}
public String getQntcommande() {
return qntcommande;
}
public void setQntcommande(String qntcommande) {
this.qntcommande = qntcommande;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
}
The form how I save data
Update 2 :
This the Adapter for the recyclerview :
public class CommandeAdapter extends
RecyclerView.Adapter<CommandeAdapter.CommandeViewHolder> {
List<Order> listArray;
public CommandeAdapter(List<Order> List) {
this.listArray = List;
}
#NonNull
#Override
public CommandeAdapter.CommandeViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.commande_model, parent, false);
return new CommandeViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull #NotNull CommandeAdapter.CommandeViewHolder holder, int position) {
CommandeViewHolder v = (CommandeViewHolder) holder;
final Order dataa = listArray.get(position);
v.nom_pdv.setText(dataa.getNompdv());
v.date.setText(dataa.getDatecommande());
v.etat.setText(dataa.getEtat());
v.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Order_detail.class);
int pos = v.getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
Order clickedDataItem = listArray.get(pos);
intent.putExtra("nompdv", clickedDataItem.getNompdv());
intent.putExtra("reference", clickedDataItem.getRefernce());
intent.putExtra("datecommande", clickedDataItem.getDatecommande());
intent.putExtra("etat", clickedDataItem.getEtat());
}
}
view.getContext().startActivity(intent);
}
});
}
public class CommandeViewHolder extends RecyclerView.ViewHolder {
TextView nom_pdv, date, etat;
public CommandeViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
nom_pdv = itemView.findViewById(R.id.namepdv);
date = itemView.findViewById(R.id.dateliv);
etat = itemView.findViewById(R.id.etat);
}
}
#Override
public int getItemCount() {
return listArray.size();
}}
And this is activity detail :
public class Order_detail extends AppCompatActivity {
TextView namepdv, refcommande, datecommande, etat, produitcmnd, qnt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_commande_detail2);
namepdv = findViewById(R.id.nompdv);
refcommande = findViewById(R.id.refcommande);
datecommande = findViewById(R.id.datecommande);
etat = findViewById(R.id.etatcommande);
// --------------------- //
namepdv.setText(getIntent().getStringExtra("nompdv"));
refcommande.setText(getIntent().getStringExtra("reference"));
datecommande.setText(getIntent().getStringExtra("datecommande"));
etat.setText(getIntent().getStringExtra("etat"));
}}

From your question I am assuming that keys under produit are random.
So when you will retrieve order details produit will be a Hashmap. Declare produit as Hashmap<String,String> in Order class.
You can print those keys and values.
for(Map.Entry<String, String> e : clickedDataItem.getproduit().entrySet()) {
// print e.getKey() e.getValue()
}

Related

java.lang.ClassCastException: java.util.HashMap cannot be cast to some random class in my app

I created an app and I store some data in a Firebase Firestore, everytime I want to fetch the data and display them in a RecyclerView I get this
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.****, PID: 9052
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.****.Models.Comments
at com.example.****.Utils.CommentsAdapter.onBindViewHolder(CommentsAdapter.java:43)
at com.example.****.Utils.CommentsAdapter.onBindViewHolder(CommentsAdapter.java:19)
....
I really don't know what I did wrong, can you please look over my code and tell me where I'm wrong?
Here's the Adapter:
public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.CommentsViewHolder> {
Context mContext;
List<Comments> mData;
public CommentsAdapter(Context mContext, List<Comments> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public CommentsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout;
layout = LayoutInflater.from(mContext).inflate(R.layout.item_comments, parent, false);
return new CommentsViewHolder(layout);
}
#Override
public void onBindViewHolder(#NonNull CommentsViewHolder holder, int i) {
//bind data
holder.title.setText(mData.get(i).getTitle());
holder.content.setText(mData.get(i).getContent());
Glide.with(mContext).load(mData.get(i).getPicUploadedBy()).into(holder.pictureProfile);
}
#Override
public int getItemCount() {
return mData.size();
}
public class CommentsViewHolder extends RecyclerView.ViewHolder {
TextView content, title;
ImageView pictureProfile;
public CommentsViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textTitle);
content = itemView.findViewById(R.id.textContent);
pictureProfile = itemView.findViewById(R.id.profileUser);
}
}
}
Here's the activity where I use this:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference("users-images");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null)
{
db.collection("Users").whereEqualTo("email", user.getEmail())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
for(QueryDocumentSnapshot documentSnapshot: task.getResult()) {
String fullname = documentSnapshot.get("fullname").toString();
String address = documentSnapshot.get("address").toString();
String city = documentSnapshot.get("city").toString();
String state = documentSnapshot.get("state").toString();
String country = documentSnapshot.get("country").toString();
String phone = documentSnapshot.get("phone").toString();
String zipcode = documentSnapshot.get("zipcode").toString();
String type = documentSnapshot.get("type").toString();
String rate = documentSnapshot.get("rate").toString();
Boolean isActivated = documentSnapshot.getBoolean("isActivated");
List<Card> cards= (List<Card>) documentSnapshot.get("cards");
List<Comments> comments = (List<Comments>) documentSnapshot.get("comments");
List<Documents> documents = (List<Documents>) documentSnapshot.get("documents");
String profilePic = documentSnapshot.get("profilePic").toString();
String email = documentSnapshot.get("email").toString();
String password = documentSnapshot.get("password").toString();
mUser = new User(
fullname,
address,
city,
state,
country,
phone,
zipcode,
type,
rate,
isActivated,
cards,
comments,
documents,
profilePic,
email,
password
);
myProfileDo(mUser);
}
}
}
});
private void myProfileDo(User mUser) {
List<Comments> commentsList = new ArrayList<>();
fullnameView.setText(mUser.getFullname());
addressView.setText(mUser.getAddress());
rateView.setText(mUser.getRate());
Glide.with(this).load(mUser.getProfilePic()).into(profilePic);
for(int i = 0 ;i < mUser.getComments().size();i++) {
commentsList.add(mUser.getComments().get(i));
}
commentsAdapter = new CommentsAdapter(this,commentsList);
rvComments.setAdapter(commentsAdapter);
rvComments.setLayoutManager(new LinearLayoutManager(this));
}
}
And The Model "Comments" :
public class Comments {
public String uploadedBy;
public String picUploadedBy;
public String title;
public String content;
public Comments(String uploadedBy, String picUploadedBy, String title, String content) {
this.uploadedBy = uploadedBy;
this.picUploadedBy = picUploadedBy;
this.title = title;
this.content = content;
}
public String getUploadedBy() {
return uploadedBy;
}
public void setUploadedBy(String uploadedBy) {
this.uploadedBy = uploadedBy;
}
public String getPicUploadedBy() {
return picUploadedBy;
}
public void setPicUploadedBy(String picUploadedBy) {
this.picUploadedBy = picUploadedBy;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
The data is fetched well, if I println the "commentsList" it's not null, must be something on the adapter or the way I implement the adapter.
Thank you in advance!

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.pasarkaget.fajar.pasarkaget.Model.Payments

I'm having a problem retrieving the payments data. It always says I can't convert object type to:
com.google.firebase.database.DatabaseException: Can't convert object
of type java.lang.String to type
com.pasarkaget.fajar.pasarkaget.Model.Payments
I'm think this error from my model payments but I don't know my mistake. Anyone can help me?
This My AdminUserPaymentsActivity where I must display the payments data certain user.
public class AdminUserPaymentActivity extends AppCompatActivity
{
private RecyclerView paymentsList;
RecyclerView.LayoutManager layoutManager;
private DatabaseReference paymentsRef;
private String userID = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_user_payments);
userID = getIntent().getStringExtra("uid");
paymentsList = findViewById(R.id.payments_list);
paymentsList.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
paymentsList.setLayoutManager(layoutManager);
paymentsRef = FirebaseDatabase.getInstance().getReference()
.child("Cart List").child("Admin View").child(userID).child("Payments");
}
#Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<Payments> options =
new FirebaseRecyclerOptions.Builder<Payments>()
.setQuery(paymentsRef, Payments.class)
.build();
FirebaseRecyclerAdapter<Payments, PaymentsViewHolder> adapter = new FirebaseRecyclerAdapter<Payments, PaymentsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull PaymentsViewHolder holder, int position, #NonNull Payments model)
{
holder.txtMyBankName.setText(model.getBuyerBank());
holder.txtBankAccountName.setText(model.getBuyerAccount());
holder.txtBankName.setText(model.getBank());
holder.txtMetods.setText(model.getMetods());
holder.txtTotalTransfer.setText("Rp " + model.getNominal());
holder.txtState.setText(model.getState());
holder.txtDate.setText("Pada Tanggal : " + model.getDate());
}
#NonNull
#Override
public PaymentsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.payments_items_layout, parent, false);
PaymentsViewHolder holder = new PaymentsViewHolder(view);
return holder;
}
};
paymentsList.setAdapter(adapter);
adapter.startListening();
}
}
My Viewholder Class
public class PaymentsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView txtBankName, txtMyBankName, txtBankAccountName, txtTotalTransfer, txtMetods, txtState, txtDate;
private ItemClickListener itemClickListener;
public PaymentsViewHolder(View itemView)
{
super(itemView);
txtBankName = itemView.findViewById(R.id.payments_bank_destination);
txtMyBankName = itemView.findViewById(R.id.payments_bank_name);
txtBankAccountName = itemView.findViewById(R.id.payments_bank_account);
txtTotalTransfer = itemView.findViewById(R.id.payments_total_transfer);
txtMetods = itemView.findViewById(R.id.payments_bank_metods);
txtState = itemView.findViewById(R.id.payments_state);
txtDate = itemView.findViewById(R.id.payments_date);
}
#Override
public void onClick(View view)
{
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
}
And Lastly, My Model Payments class
public class Payments
{
private String bank, buyerBank, buyerAccount, nominal, metods, state, date, time;
public Payments()
{
}
public Payments(String bank, String buyerBank, String buyerAccount, String nominal, String metods, String state, String date, String time)
{
this.bank = bank;
this.buyerBank = buyerBank;
this.buyerAccount = buyerAccount;
this.nominal = nominal;
this.metods = metods;
this.state= state;
this.date = date;
this.time = time;
}
public String getBank() {
return bank;
}
public void setBank(String bank) {
this.bank = bank;
}
public String getBuyerBank() {
return buyerBank;
}
public void setBuyerBank(String buyerBank) {
this.buyerBank = buyerBank;
}
public String getBuyerAccount() {
return buyerAccount;
}
public void setBuyerAccount(String buyerAccount) {
this.buyerAccount = buyerAccount;
}
public String getNominal() {
return nominal;
}
public void setNominal(String nominal) {
this.nominal = nominal;
}
public String getMetods() {
return metods;
}
public void setMetods(String metods) {
this.metods = metods;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
My Firebase database structured:
my structured firebase
When you are passing your paymentsRef to the FirebaseRecyclerOptions<Payments> object it means that you are looking for Payments objects but within your reference, there are only objects of type String and not Payments, and that's why you get that error. To solve this, simply remove the call to .child("Payments"):
paymentsRef = FirebaseDatabase.getInstance().getReference()
.child("Cart List").child("Admin View").child(userID);
And you'll be able to get all Payments objects that exist within your userID node.

Firebase model POJO getter returns null in FirebaseRecyclerAdapter

I have a FirebaseRecyclerAdapter fetching data from the firebase database but when I am trying to access firebase data the getter method of the POJO returns null. I am able to get the database reference key.
final Query beveragesQuery = mDatabaseReference.child(FirebaseValues.PRODUCTS)
.child(FirebaseValues.BEVERAGES);
FirebaseRecyclerOptions<GenericProductModel> beveragesOptions =
new FirebaseRecyclerOptions.Builder<GenericProductModel>()
.setQuery(beveragesQuery, GenericProductModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<GenericProductModel, Combos.MovieViewHolder>(
beveragesOptions
) {
#NonNull
#Override
public Combos.MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_cardview_layout, parent, false);
return new Combos.MovieViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Combos.MovieViewHolder viewHolder, int position, #NonNull GenericProductModel model) {
Log.d(TAG, "Item received:"+getRef(position).getKey());
String json = new Gson().toJson(model);
Log.d(TAG, "Item received:"+ json);
Log.d(TAG, "Item received:"+ model.toString());
if (tv_no_item.getVisibility() == View.VISIBLE) {
tv_no_item.setVisibility(View.GONE);
}
Log.d(TAG, "card name:"+model.getCardname());
viewHolder.cardname.setText(model.getCardname());
viewHolder.cardprice.setText("₹ " + Float.toString(model.getCardprice()));
Picasso.get().load(model.getCardimage()).into(viewHolder.cardimage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Beverages.this, IndividualProduct.class);
intent.putExtra("product", getItem(position));
startActivity(intent);
}
});
}
#Override
public void onError(DatabaseError e) {
Log.e(TAG, "RV Adapter, Error occurred: " + e.getMessage());
}
};
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
adapter.startListening();
mRecyclerView.setAdapter(adapter);
}
My POJO or model class is
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
I am implementing Serializable because I am sending this data as an intent to other activity.
Added some more log options for clearity
When I run the app the log output I am getting is:
03-17 15:05:55.200 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received, received:1
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:{"a":0,"e":0.0}
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:com.vdeveloper.chaisutta.b.a#63d3fc
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: card name:null
Database Screenshot:
I have found a solution myself. The problem was with my POJO. As this project was on androidx I need to add the annotation "#Keep" to stop the compiler from removing methods which it thinks are redundant.
import java.io.Serializable;
import androidx.annotation.Keep;
#Keep
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
Thanks, everyone for helping
You are getting null because all your values are null since you are returning in each getter this.fieldName instead of the fieldName. To solve this, please change your getters to:
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
See, there is no this anymore.

Issue with ArrayList from JSON using Retrofit and populating RecyclerView

I’ve been trying to get recycler view working with retrofit. I seem to be pulling in the JSON fine from within getRecipes() method, and my logs are showing me that the some data is there.
However, when I call my getRecipes() method from onCreate(), something seems to be going wrong. When I check to see if my recipeList array contains my JSON results within onCreate, it is telling me it is empty. Why is it doing this if my logs within my getRecipes() method are showing me that data is there...?
Not sure if it is an issue with my recycler view or what I am doing with retrofit, or something else. Been trying for days to figure out, so any advice would be greatly appreciated.
JSON
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
public class ItemListActivity extends AppCompatActivity {
private boolean mTwoPane;
public static final String LOG_TAG = "myLogs";
public static List<Recipe> recipeList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getRecipes();
setContentView(R.layout.activity_item_list);
getRecipes();
//Logging to check that recipeList contains data
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.item_list);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
}
public void getRecipes(){
String ROOT_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/";
Retrofit RETROFIT = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RecipeService service = RETROFIT.create(RecipeService.class);
Call<List<Recipe>> call = service.getMyJson();
call.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {
Log.d(LOG_TAG, "Got here");
if (!response.isSuccessful()) {
Log.d(LOG_TAG, "No Success");
}
Log.d(LOG_TAG, "Got here");
recipeList = response.body();
//Logging to check data is there
Log.v(LOG_TAG, "LOGS" + recipeList.size());
for (int i = 0; i < recipeList.size(); i++) {
String newString = recipeList.get(i).getName();
Ingredients[] ingredients = recipeList.get(i).getIngredients();
for(int j = 0; j < ingredients.length; j++){
Log.d(LOG_TAG, ingredients[j].getIngredient());
}
Steps[] steps = recipeList.get(i).getSteps();
for(int k = 0; k < steps.length; k++){
Log.d(LOG_TAG, steps[k].getDescription());
}
Log.d(LOG_TAG, newString);
}
}
#Override
public void onFailure(Call<List<Recipe>> call, Throwable t) {
Log.e("getRecipes throwable: ", t.getMessage());
t.printStackTrace();
}
});
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<Recipe> mValues;
public SimpleItemRecyclerViewAdapter(List<Recipe> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getName());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View mView;
public TextView mContentView;
public Recipe mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
RecipeService
public interface RecipeService {
#GET("baking.json")
Call<List<Recipe>> getMyJson();}
Models
Recipe
public class Recipe{
private Ingredients[] ingredients;
private String id;
private String servings;
private String name;
private String image;
private Steps[] steps;
public Ingredients[] getIngredients ()
{
return ingredients;
}
public void setIngredients (Ingredients[] ingredients)
{
this.ingredients = ingredients;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getServings ()
{
return servings;
}
public void setServings (String servings)
{
this.servings = servings;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
public Steps[] getSteps ()
{
return steps;
}
public void setSteps (Steps[] steps)
{
this.steps = steps;
}
#Override
public String toString()
{
return "[ingredients = "+ingredients+", id = "+id+", servings = "+servings+", name = "+name+", image = "+image+", steps = "+steps+"]";
}}
Ingredients
public class Ingredients{
private String measure;
private String ingredient;
private String quantity;
public String getMeasure ()
{
return measure;
}
public void setMeasure (String measure)
{
this.measure = measure;
}
public String getIngredient ()
{
return ingredient;
}
public void setIngredient (String ingredient)
{
this.ingredient = ingredient;
}
public String getQuantity ()
{
return quantity;
}
public void setQuantity (String quantity)
{
this.quantity = quantity;
}
#Override
public String toString()
{
return "[measure = "+measure+", ingredient = "+ingredient+", quantity = "+quantity+"]";
}}
Steps
public class Steps{
private String id;
private String shortDescription;
private String description;
private String videoURL;
private String thumbnailURL;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getShortDescription ()
{
return shortDescription;
}
public void setShortDescription (String shortDescription)
{
this.shortDescription = shortDescription;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getVideoURL ()
{
return videoURL;
}
public void setVideoURL (String videoURL)
{
this.videoURL = videoURL;
}
public String getThumbnailURL ()
{
return thumbnailURL;
}
public void setThumbnailURL (String thumbnailURL)
{
this.thumbnailURL = thumbnailURL;
}
#Override
public String toString()
{
return "[id = "+id+", shortDescription = "+shortDescription+", description = "+description+", videoURL = "+videoURL+", thumbnailURL = "+thumbnailURL+"]";
}}
Logs
https://gist.github.com/2triggers/12b6eeb32ed8909ab50bbadd4742d7f7
this will be empty always because this line will execute before getting the response from a server.
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Better call this after this line recipeList = response.body();
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
it is because you are sending the recipelist into the adapter before even it is populated , after you are sending the recipelist into the adapter which is empty you are populating your recipelist from getRecipes method, you might be wondering you have declared the getRecipes method before even you are assigning the recipelist to adapter so how come it is empty, yea but the fact is your getRecipes work on background thread so even before your recipelist gets populated your adapter assignment takes place on the main thread so you are basically assigning the empty list, one thing you can do is notify when the adapter when the data changes or when the the recipelist is filled with data that is from within the getRecipe method.
when you assign the recipelist = response.body right after this you can notify the adapter
or move this two lines
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
right after the
recipelist = response.body;
in getRecipes method
Try create the Constructor with all atributes from your Recipe.class
Like:
public Ingredients(String measure, String ingredients, String quantity ){
this.measure = measure;
this.ingredients = ingredients;
this.quantity = quantity
}
Do same in all class where make up your object of list.

Having troubles getting data from List Adapter for OnItemClick

Im having an issue with getting data that is obtained when my listadapter is set to my listview. Im trying to get this data in onItemClick so that i can put it into my intent extra's for my other activity to obtain.
The Problem
Currently i've created null string variables and then in my adapter assigning the strings with the desired text by methods within my model. However the problem im having is that the text that is being pulled is not the correct text for the position that onitemclick was called for.
Here some code...
XMLParseActivity
public class XMLParseActivity extends Activity implements AdapterView.OnItemClickListener {
private ListView mIssueListView;
private IssueParser mIssueParser;
private List<IssueFeed> mIssueList;
private IssueAdapter mIssueAdapter;
private String result_connectedtype = "";
private String result_symptom = "";
private String result_problem = "";
private String result_solution = "";
private String result_comments = "";
...
public class IssueAdapter extends ArrayAdapter<IssueFeed> {
public List<IssueFeed> issueFeedList;
public IssueAdapter(Context context, int textViewResourceId, List<IssueFeed> issueFeedList) {
super(context, textViewResourceId, issueFeedList);
this.issueFeedList = issueFeedList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
IssueHolder issueHolder = null;
if (convertView == null) {
view = View.inflate(XMLParseActivity.this, R.layout.issue_list_item, null);
issueHolder = new IssueHolder();
issueHolder.issueConnectedType = (TextView) view.findViewById(R.id.result_connected_type);
issueHolder.issueSymptomView = (TextView) view.findViewById(R.id.result_symptom);
view.setTag(issueHolder);
} else {
issueHolder = (IssueHolder) view.getTag();
}
IssueFeed issueFeed = issueFeedList.get(position);
issueHolder.issueConnectedType.setText(issueFeed.getConnected_type());
issueHolder.issueSymptomView.setText(issueFeed.getSymptom());
//THE DATA I WANT TO USE IN MY INTENT
result_solution = issueFeed.getSolution();
result_comments = issueFeed.getComments();
result_connectedtype = issueFeed.getConnected_type();
result_problem = issueFeed.getProblem();
result_symptom = issueFeed.getSymptom();
return view;
}
}
static class IssueHolder {
public TextView issueSymptomView;
public TextView issueConnectedType;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
//Put the strings in intent extra
Intent intent = new Intent(this, SpecificIssueActivity.class);
intent.putExtra("symptom", result_symptom);
intent.putExtra("problem", result_problem);
intent.putExtra("solution", result_solution);
intent.putExtra("comments", result_comments);
intent.putExtra("connectedtype", result_connectedtype);
startActivity(intent);
}
The listAdapter is set in a asynctask in the below code
public class DoLocalParse extends AsyncTask<String, Void, List<IssueFeed>> {
ProgressDialog prog;
String jsonStr = null;
Handler innerHandler;
#Override
protected void onPreExecute() {
prog = new ProgressDialog(XMLParseActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected List<IssueFeed> doInBackground(String... params) {
mIssueParser = new IssueParser(null);
mIssueList = mIssueParser.parseLocally(params[0]);
return mIssueList;
}
#Override
protected void onPostExecute(List<IssueFeed> result) {
prog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
mIssueAdapter = new IssueAdapter(XMLParseActivity.this, R.layout.issue_list_item,
mIssueList);
int count = mIssueAdapter.getCount();
if (count != 0 && mIssueAdapter != null) {
mIssueListView.setAdapter(mIssueAdapter);
}
}
});
}
}
And my model IssueFeed looks like this
public class IssueFeed implements Serializable {
private String connected_type;
private String symptom;
private String problem;
private String solution;
private String comments;
public IssueFeed() {
}
public IssueFeed(String connected_type, String symptom, String problem, String solution, String comments) {
this.connected_type = connected_type;
this.symptom = symptom;
this.problem = problem;
this.solution = solution;
this.comments = comments;
}
public String getConnected_type() {
return connected_type;
}
public String getSymptom() {
return symptom;
}
public String getProblem() {
return problem;
}
public String getSolution() {
return solution;
}
public String getComments() {
return comments;
}
public void setConnected_type(String connected_type) {
this.connected_type = connected_type;
}
public void setSymptom(String symptom) {
this.symptom = symptom;
}
public void setProblem(String problem) {
this.problem = problem;
}
public void setSolution(String solution) {
this.solution = solution;
}
public void setComments(String comments) {
this.comments = comments;
}
}
I have solve the issue by getting the data from some simple methods in my model to obtain the values.

Categories

Resources