RecyclerView populating each item every time i add a new item - java

I'm trying to make a replica chat app and I have a list that I need populated into the recyclerview. I'm getting data from firebase realtime database and every time I receive or actually send a message, All the previous item(messages) plus the new one are repopulated/duplicated into the recycler view.
What I have tried
I have tried using .cleaar() method on my list before adding a new item to the list but now all other items in the recycler view disappear
here's my adapter
public class MessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
FirebaseUser firebaseUser;
private Context ctx;
private List<Messages> msgsR, msgsS;//ignore unused
private ArrayList<Messages> dataSet;
public MessageAdapter(Context context) {
this.ctx = context;
this.dataSet = new ArrayList<>();
//this.msgsR = messagesReceived;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == Messages.SENT_TYPE) {
View view = LayoutInflater.from(ctx).inflate(R.layout.message_item_right, parent, false);
return new ViewHolderS(view);
}
if (viewType == Messages.RECEIVED_TYPE) {
View view = LayoutInflater.from(ctx).inflate(R.layout.message_item_left, parent, false);
return new ViewHolderR(view);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Messages object = dataSet.get(position);
if (object != null) {
switch (object.type) {
case Messages.RECEIVED_TYPE:
((ViewHolderR) holder).populate(object, position);
break;
case Messages.SENT_TYPE:
((ViewHolderS) holder).populate(object, position);
break;
}
}
}
//recceives messages object to populate into list
//it does not matter where i put the .clear() method, after or below dataset.add() its still undesireable
public void addMessageSent(Messages messages){
dataSet.clear();
dataSet.add(messages);
// notifyItemInserted(dataSet.size()-1);
//notifyItemRangeChanged(dataSet.size()-1, dataSet.size());
}
#Override
public int getItemCount() {
return dataSet.size();
}
// sent messages are handled here
public static class ViewHolderS extends RecyclerView.ViewHolder {
public TextView msg, time;
public LinearLayout layout;
public ViewHolderS(#NonNull View itemView) {
super(itemView);
layout = itemView.findViewById(R.id.cont);
msg = itemView.findViewById(R.id.send_msg);
time = itemView.findViewById(R.id.time);
}
private void populate(Messages messages, int position) {
msg.setText(messages.getMessage());
msg.setPadding(6, 4, 18, 4);
msg.setMinWidth(100);
msg.setMaxWidth(400);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) msg.getLayoutParams();
layoutParams.gravity = Gravity.START;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.topMargin = layoutParams.bottomMargin = layoutParams.rightMargin = 10;
layoutParams.leftMargin = 20;
msg.setLayoutParams(layoutParams);
time.setText(messages.getTime());
}
}
#Override
public int getItemViewType(int position) {
switch (dataSet.get(position).type) {
case 0:
return Messages.SENT_TYPE;
case 1:
return Messages.RECEIVED_TYPE;
default:
return -1;
}
}
// received messages are handled here
private class ViewHolderR extends ViewHolderS {
public TextView msg, time;
public LinearLayout layout;
public ViewHolderR(#NonNull View itemView) {
super(itemView);
layout = itemView.findViewById(R.id.cont);
msg = itemView.findViewById(R.id.send_msg);
time = itemView.findViewById(R.id.time);
}
private void populate(Messages messages, int position) {
msg.setText(messages.getMessage());
msg.setPadding(6, 4, 18, 4);
msg.setMinWidth(100);
msg.setMaxWidth(400);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) msg.getLayoutParams();
layoutParams.gravity = Gravity.START;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.topMargin = layoutParams.bottomMargin = layoutParams.rightMargin = 10;
layoutParams.leftMargin = 20;
msg.setLayoutParams(layoutParams);
time.setText(messages.getTime());
}
}
}
and here's my data model
public class Messages {
private String message;
public static final int SENT_TYPE=0;
public static final int RECEIVED_TYPE=1;
public static final int AUDIO_TYPE=2;
private long time;
public int type;
private String id;
private String receiver;
public Messages(String message,long time, String sender,String receiver, int type) {
this.message = message;
this.time = time;
this.id = sender;
this.type = type;
this.receiver = receiver;
}
public Messages() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTime() {
SimpleDateFormat output = new SimpleDateFormat("HH:mm", Locale.getDefault());
return output.format(new Date(time));
}
public void setTime(long time) {
this.time = time;
}
public String getSender() {
return id;
}
public void setSender(String sender) {
this.id = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
}
and below is activity class where I set the adapter and fill the list
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
list= new ArrayList();
messageAdapter = new MessageAdapter(PersonChatActivity.this);
recyclerView.setAdapter(messageAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
if (Objects.requireNonNull(recyclerView.getAdapter()).getItemCount() > 0) {
recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount());
}
//get sent messages from firebase
private void getmessages() {
DatabaseReference reference = database.getReference("Chats");
reference.keepSynced(true);
reference.child(senderId).child(receiver).push();
reference.child(senderId).child(receiver).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageSent.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.getValue() != null) {
String message = (String) dataSnapshot.child("message").getValue();
long time = (Long) dataSnapshot.child("time").getValue();
String senderId = (String) dataSnapshot.child("id").getValue();
String receiverId = (String) dataSnapshot.child("receiver").getValue();
assert firebaseUser != null;
String user = firebaseUser.getUid();
Messages msg = new Messages(message, time, senderId, receiverId,Messages.SENT_TYPE);
String Uid = msg.getSender();
if (!Uid.isEmpty() && Uid.equals(user)) {
//pass the new message object to messages adapter to fill the list
messageAdapter.addMessageSent(msg);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
EDIT UPDATE
As suggested I have made the necessary changes and code works like magic
I wont update the right changes into the question in case someone makes the same mistake as I have plus the comment marked as answer basically highlights the correct changes,,
NEW PROBLEM
The new problem is, on adding object message to the addMessagesent() previously populated recyclerview items get replaced by the new data.
to make it easy, on receiving a new message, all the previous visible sent messagees disappear and are replaced by the new received messages
here is my getmessageReceived() method
DatabaseReference reference = database.getReference("Chats");
reference.keepSynced(true);
reference.child(receiver).child(senderId).push();
reference.child(receiver).child(senderId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageReceived.clear();
messageAdapter.clearAllMessage();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.getValue() != null) {
String message = (String) dataSnapshot.child("message").getValue();
long time = (Long) dataSnapshot.child("time").getValue();
String senderId = (String) dataSnapshot.child("id").getValue();
String receiverId = (String) dataSnapshot.child("receiver").getValue();
assert firebaseUser != null;
String user = firebaseUser.getUid();
Messages msg = new Messages(message, time, senderId, receiverId,Messages.RECEIVED_TYPE);
String Uid = msg.getReceiver();
if (!Uid.isEmpty() && Uid.equals(user)) {
messageAdapter.addMessageSent(msg);
messageAdapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}

You should not clear the data set in the addMessageSent() just add new item to data set as shown below
public void addMessageSent(Messages messages){
dataSet.add(messages);
}
and create a new method to clear the dataset in your adapter
public void clearAllMessage(){
dataSet.clear();
}
And in getmessages() call clearAllMessage() like this
private void getmessages() {
DatabaseReference reference = database.getReference("Chats");
reference.keepSynced(true);
reference.child(senderId).child(receiver).push();
reference.child(senderId).child(receiver).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageSent.clear();
clearAllMessage();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.getValue() != null) {
String message = (String) dataSnapshot.child("message").getValue();
long time = (Long) dataSnapshot.child("time").getValue();
String senderId = (String) dataSnapshot.child("id").getValue();
String receiverId = (String) dataSnapshot.child("receiver").getValue();
assert firebaseUser != null;
String user = firebaseUser.getUid();
Messages msg = new Messages(message, time, senderId, receiverId,Messages.SENT_TYPE);
String Uid = msg.getSender();
if (!Uid.isEmpty() && Uid.equals(user)) {
//pass the new message object to messages adapter to fill the list
messageAdapter.addMessageSent(msg);
messageAdapter.notifyDataSetChanged(); // Call this also
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}

Related

How to retrieve data from database using hashmap?

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()
}

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!

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.

Getter and setter not working as expected in recyclerview android

I am getting json values from volley post request. I am adding those values to list using setter method. When i am retrieving values in adapter onBindViewholder() method and displaying it in a recyclerview result is not getting displayed as expected:
Below code refers to adding values to list from volley request and response in MainActivity.java:
private ProductsPojo pojo;
public static ProductsAdapter productsAdapter;
private List<ProductsPojo> pojoList;
pojo = new ProductsPojo();
pojoList = new ArrayList<>();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Appet8","Products response:"+response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray products = jsonObject.getJSONArray("products");
for (int i=0;i<products.length();i++) {
JSONObject product_object = products.getJSONObject(i);
String name = product_object.getString("name");
String price = product_object.getString("price");
String product_id = product_object.getString("id");
String sessionname = product_object.getString("sessionname");
String image = product_object.getString("image");
String categoryname = product_object.getString("categoryname");
pojo.setName(product_object.getString("name"));
pojo.setImage(product_object.getString("image"));
pojoList.add(pojo);
}
productsAdapter = new ProductsAdapter(pojoList,getApplicationContext());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("customer_id", customer_id);
return params;
}
};
AppController.getInstance().addToRequestQueue(request,tag_request);
Below code refers to setting adapter to recyclerview in a ProductFragment.java:
private GridLayoutManager layoutManager;
private RecyclerView recyclerView;
recyclerView = (RecyclerView) view.findViewById(R.id.productList);
recyclerView.setHasFixedSize(true);
layoutManager = new GridLayoutManager(getActivity().getApplicationContext(),3);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(MainActivity.productsAdapter);
Below code refers to adapter class which displays values, ProductsAdapter.java:
public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductsViewHolder> {
private List<ProductsPojo> productList;
private Context context;
public ProductsAdapter(List<ProductsPojo> productList,Context context) {
this.productList=productList;
this.context = context;
}
#Override
public ProductsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.products_list, parent, false);
ProductsViewHolder holder = new ProductsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProductsViewHolder holder,final int position) {
final ProductsPojo pojo = productList.get(position);
Log.d("Appet8","Name:"+pojo.getName());
holder.vTitle.setText(pojo.getName());
holder.vTitle.setTypeface(MainActivity.font);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pojo.setSelected(!pojo.isSelected());
holder.itemView.setBackgroundColor(pojo.isSelected() ? Color.parseColor("#4D79CF08") : Color.parseColor("#2D6F6F6F"));
if(pojo.isSelected()) {
holder.selected.setVisibility(View.VISIBLE);
} else if(!pojo.isSelected()) {
holder.selected.setVisibility(View.GONE);
}
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public static class ProductsViewHolder extends RecyclerView.ViewHolder {
protected TextView vTitle;
protected ImageView image,selected;
protected CardView product_card;
public ProductsViewHolder(View v) {
super(v);
vTitle = (TextView) v.findViewById(R.id.title);
image = (ImageView) v.findViewById(R.id.product);
product_card = (CardView) v.findViewById(R.id.product_card);
selected = (ImageView) v.findViewById(R.id.selected);
}
}
}
This is the response that i get from volley request:
{
"products":[
{
"name":"Idli",
"price":"120",
"id":"Fi2mYuQA",
"sessionname":"Breakfast",
"image":"VCYwmSae2BShoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
},
{
"name":"Meals123",
"price":"200",
"id":"bmF8Is1Y",
"sessionname":"Dinner",
"image":"sIe8JBFzaRstock-photo-115193575.jpg",
"categoryname":"Non Veg"
},
{
"name":"Dosa",
"price":"100",
"id":"e9sWHV4A",
"sessionname":"Breakfast",
"image":"j8nu4GpVa7Shoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
},
{
"name":"Coca",
"price":"40",
"id":"0oJDfdCz",
"sessionname":"Cold Drinks",
"image":"LrkS8QpAs7Shoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
},
{
"name":"ICe",
"price":"100",
"id":"2ykEgtSs",
"sessionname":null,
"image":"KtPX9C26oRShoshone_Falls-1200px.jpeg",
"categoryname":"Veg"
}
]
}
This is the output i am getting. Item names are repeated.
Below code Refers to ProductsPojo.java:
public class ProductsPojo {
public String name;
public String image;
private boolean isSelected = false;
public void setName(String name) {
this.name = name;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public String getImage() {
return image;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
Looks to me like you only ever create one ProductsPojo instance, here:
pojo = new ProductsPojo();
And then in your loop you keep modifying this one instance, and then adding it to the list again and again. This way you'd end up with the same item (the last one) in your list as many times as the number of objects you got in the response.
What you wanted to do was probably to create a new ProductsPojo at the beginning of the for loop every time instead, like this:
for (int i=0;i<products.length();i++) {
ProductsPojo pojo = new ProductsPojo();
JSONObject product_object = products.getJSONObject(i);
String name = product_object.getString("name");
String price = product_object.getString("price");
String product_id = product_object.getString("id");
String sessionname = product_object.getString("sessionname");
String image = product_object.getString("image");
String categoryname = product_object.getString("categoryname");
pojo.setName(product_object.getString("name"));
pojo.setImage(product_object.getString("image"));
pojoList.add(pojo);
}

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