Organizing messages in user chat activity - java

i have created a custom view holder for my app to position sent messages to the right and received messages to the left which is working.
when messages are sent or received they are positioned as expected but when the chat activity is closed and reopened both the sent and received messages are positioned to the left and given the same color.
how can i make it remain as it is even when the app is closed and reopened?
below is my MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter {
private static final int VIEW_TYPE_MESSAGE_SENT = 1;
private static final int VIEW_TYPE_MESSAGE_RECEIVED = 2;
private FirebaseAuth mAuth;
private Context mContext;
private List<Messages> mMessageList;
public MessageAdapter(List<Messages> mMessageList) {
//mContext = context;
this.mMessageList = mMessageList;
}
#Override
public int getItemCount() {
return mMessageList.size();
}
// Determines the appropriate ViewType according to the sender of the message.
#Override
public int getItemViewType(int i) {
mAuth = FirebaseAuth.getInstance();
String current_user_id = mAuth.getCurrentUser().getUid();
Messages c = mMessageList.get(i);
String from_user = c.getFrom();
String message_type = c.getType();
if (from_user == (current_user_id)) {
return VIEW_TYPE_MESSAGE_SENT;
} else {
return VIEW_TYPE_MESSAGE_RECEIVED;
}
}
// Inflates the appropriate layout according to the ViewType.
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent,int viewType){
View view;
if (viewType == VIEW_TYPE_MESSAGE_SENT) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_message_sent, parent, false);
return new SentMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_RECEIVED) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_message_received, parent, false);
return new ReceivedMessageHolder(view);
}
return null;
}
// Passes the message object to a ViewHolder so that the contents can be bound to UI.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {
Messages c = mMessageList.get(i);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_SENT:
((SentMessageHolder) holder).bind(c);
break;
case VIEW_TYPE_MESSAGE_RECEIVED:
((ReceivedMessageHolder) holder).bind(c);
}
}
private class SentMessageHolder extends RecyclerView.ViewHolder {
TextView messageText, timeText;
SentMessageHolder(View itemView) {
super(itemView);
messageText = (TextView) itemView.findViewById(R.id.text_message_body);
timeText = (TextView) itemView.findViewById(R.id.text_message_time);
}
void bind(Messages message) {
messageText.setText(message.getMessage());
// Format the stored timestamp into a readable String using method.
// timeText.setText(Utils.formatDateTime(message.getCreatedAt()));
}
}
private class ReceivedMessageHolder extends RecyclerView.ViewHolder {
TextView messageText, timeText, nameText;
ImageView profileImage;
ReceivedMessageHolder(View itemView) {
super(itemView);
messageText = (TextView) itemView.findViewById(R.id.text_message_body);
timeText = (TextView) itemView.findViewById(R.id.text_message_time);
}
void bind(Messages message) {
messageText.setText(message.getMessage());
}
}
}
and my ChatActivity.java
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = inflater.inflate(R.layout.child_custom_layout,null);
actionBar.setCustomView(action_bar_view);
mTitleView = findViewById(R.id.custom_bar_title);
mLastSeenView = findViewById(R.id.custom_bar_seen);
mProfileImage = findViewById(R.id.custom_appbar_image);
mChatAddBtn = findViewById(R.id.chat_add_btn);
mChatSendBtn = findViewById(R.id.chat_send_btn);
mChatMessageView = findViewById(R.id.chat_message_view);
mChatAddBtn.setVisibility(View.INVISIBLE);
mChatAddBtn.setEnabled(false);
mTitleView.setText(userName);
mAdapter = new MessageAdapter(messagesList);
mMessagesList = findViewById(R.id.messages_list);
mRefreshLayout = findViewById(R.id.message_swipe_layout);
mLinearLayout = new LinearLayoutManager(this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
mMessagesList.setAdapter(mAdapter);
// loadMessages();
mImageStorage = FirebaseStorage.getInstance().getReference();
mRootRef.child("Chat").child(mCurrentUserId).child(mChatUser).child("seen").setValue(true);
loadMessages();

Here is the problem in the code
if (from_user == (current_user_id)) {
return VIEW_TYPE_MESSAGE_SENT;
} else {
return VIEW_TYPE_MESSAGE_RECEIVED;
}
You are checking equivalency with ==. This is not the right way of checking string equivalency. If you want to check equivalency you need to call equals() method of string as mentioned in below code.
if (from_user.equals(current_user_id)) {
return VIEW_TYPE_MESSAGE_SENT;
} else {
return VIEW_TYPE_MESSAGE_RECEIVED;
}
Try this. Hope this will help you.

Related

Nested RecyclerView doesn't react to notify functions

I have a problem when working with nested RecyclerView in RecyclerView. In my parent RecyclerView I am displaying rows of items. These rows have rows of scanned goods. If I want to display the scanned rows, I click on the parent Recyclerview and it expands. When I tap on the child RecyclerView, it should show edit/delete buttons instead of an error message. Notify works until I shrink the parent RecyclerView(tap it again) and expand it again. At the moment notify does not trigger onBindViewHolder.
Anyone know what to do?
Parent Fragment
public class ShowCdlFragment extends Fragment {
private FragmentShowCdlBinding binding;
private Resources res;
private SessionManager session;
private Bundle params;
private F1002dlh f1002dlh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.binding = FragmentShowCdlBinding.inflate(getLayoutInflater());
this.session = new SessionManager(getContext());
this.res = getResources();
this.session.checkLogin(getActivity());
// Inflate the layout for this fragment
return this.binding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.params = getArguments();
this.f1002dlh = this.params.getParcelable("F1002DLH");
RecyclerView rvMenu = (RecyclerView) binding.showCdlRecyclerView;
ArrayList<F1002dlr> f1002dlrArrayList = this.f1002dlh.getF1002dlh_f1002dlrs();
CdlAdapter cdlAdapter = new CdlAdapter(f1002dlrArrayList, getContext());
rvMenu.setAdapter(cdlAdapter);
rvMenu.setLayoutManager(new LinearLayoutManager(this.getContext()));
}
}
Parent Adapter
public class CdlAdapter extends RecyclerView.Adapter<CdlAdapter.ViewHolder> {
private List<F1002dlr> f1002dlrList;
private Context context;
private Integer expandedPosition = -1;
private RecyclerView.RecycledViewPool recycledViewPool;
private RecyclerView cdlItem_sub_recyclerView;
public CdlAdapter(List<F1002dlr> f1002dlrList, Context context) {
this.f1002dlrList = f1002dlrList;
this.context = context;
this.recycledViewPool = new RecyclerView.RecycledViewPool();
}
#NonNull
#Override
public CdlAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View cdlView = inflater.inflate(R.layout.cdl_item, parent, false);
return new ViewHolder(cdlView);
}
#Override
public void onBindViewHolder(#NonNull CdlAdapter.ViewHolder holder, int position) {
F1002dlr f1002dlr = f1002dlrList.get(position);
ImageView f1002dlr_status_imageView = holder.f1002dlr_status_imageView;
TextView f1002dlr_vpd_textView = holder.f1002dlr_vpd_textView;
TextView f1002dlr_radek_textView = holder.f1002dlr_radek_textView;
TextView f1002dlr_komodita_textView = holder.f1002dlr_komodita_textView;
TextView f1002dlr_xvyr_textView = holder.f1002dlr_xvyr_textView;
TextView f1002dlr_jakost_textView = holder.f1002dlr_jakost_textView;
TextView f1002dlr_mnozstvi_textView = holder.f1002dlr_mnozstvi_textView;
TextView f1002dlr_vady_textView = holder.f1002dlr_vady_textView;
TextView f1002dlr_mj_textView = holder.f1002dlr_mj_textView;
TextView f1002dlr_hodnota_textView = holder.f1002dlr_hodnota_textView;
TextView f1002dlr_pc_textView = holder.f1002dlr_pc_textView;
f1002dlr_status_imageView.setImageResource(getImageId(f1002dlr.getStatus()));
f1002dlr_vpd_textView.setText(f1002dlr.getF1002dlr_vpd().toString());
f1002dlr_radek_textView.setText(f1002dlr.getF1002dlr_radek().toString());
f1002dlr_komodita_textView.setText(f1002dlr.getF1002dlr_komodita());
f1002dlr_xvyr_textView.setText(f1002dlr.getF1002dlr_xvyr().toString());
f1002dlr_jakost_textView.setText(f1002dlr.getF1002dlr_jakost());
f1002dlr_mnozstvi_textView.setText(String.format("%.2f", f1002dlr.getF1002dlr_mnozstvi()));
f1002dlr_vady_textView.setText(f1002dlr.getF1002dlr_vady().toString());
f1002dlr_mj_textView.setText(f1002dlr.getF1002dlr_mj());
f1002dlr_hodnota_textView.setText(String.format("%.2f", f1002dlr.getHodnota()));
f1002dlr_pc_textView.setText(String.format("%.2f", f1002dlr.getF1002dlr_pc()));
Double mnozstvi = 0.00;
Integer vady = 0;
for (F1002ck_data f1002ck_data : f1002dlr.getF1002dlr_f1002ck_datas()) {
mnozstvi += f1002ck_data.getF1002ck_data_mnozstvi_mj1();
vady += f1002ck_data.getF1002ck_data_vady();
}
TextView nasnimane_mnozstvi_textView = holder.nasnimane_mnozstvi_textView;
TextView nasnimane_vady_textView = holder.nasnimane_vady_textView;
nasnimane_mnozstvi_textView.setText(String.format("%.2f", mnozstvi));
nasnimane_vady_textView.setText(vady.toString());
if (expandedPosition == -1) {
f1002dlr.setExpanded(false);
}
Boolean isExpanded = f1002dlr.getExpanded();
if (isExpanded) {
holder.expandable_constraintLayout.setVisibility(View.VISIBLE);
} else {
holder.expandable_constraintLayout.setVisibility(View.GONE);
}
cdlItem_sub_recyclerView = holder.cdlItem_sub_recyclerView;
LinearLayoutManager layoutManager = new LinearLayoutManager(cdlItem_sub_recyclerView.getContext(), LinearLayoutManager.VERTICAL, false);
cdlItem_sub_recyclerView.setLayoutManager(layoutManager);
cdlItem_sub_recyclerView.setAdapter(new CdlSubAdapter(f1002dlr.getF1002dlr_f1002ck_datas(), context));
cdlItem_sub_recyclerView.setRecycledViewPool(recycledViewPool);
}
private void updateF1002dlh() {
if (context instanceof AdapterCallInterface) {
((AdapterCallInterface) context).setDocumentData(f1002dlrList);
}
}
private int getImageId(int status) {
Integer imageId = 0;
switch (status) {
case -2:
imageId = R.drawable.orange_status;
break;
case -1:
imageId = R.drawable.red_status;
break;
case 0:
imageId = R.drawable.grey_status;
break;
case 1:
imageId = R.drawable.green_status;
break;
}
return imageId;
}
#Override
public int getItemCount() {
return f1002dlrList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView f1002dlr_status_imageView;
private TextView f1002dlr_vpd_textView;
private TextView f1002dlr_radek_textView;
private TextView f1002dlr_komodita_textView;
private TextView f1002dlr_xvyr_textView;
private TextView f1002dlr_jakost_textView;
private TextView f1002dlr_mnozstvi_textView;
private TextView f1002dlr_vady_textView;
private TextView f1002dlr_mj_textView;
private TextView f1002dlr_hodnota_textView;
private TextView f1002dlr_pc_textView;
private TextView nasnimane_mnozstvi_textView;
private TextView nasnimane_vady_textView;
private LinearLayout linearLayout;
private ConstraintLayout main_constrainLayout;
private ConstraintLayout expandable_constraintLayout;
private ConstraintLayout second_constraintLayout;
private RecyclerView cdlItem_sub_recyclerView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
initAdapterViews();
second_constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
F1002dlr f1002dlr;
if (expandedPosition >= 0 && expandedPosition != getAdapterPosition()) {
int prev = expandedPosition;
f1002dlr = f1002dlrList.get(prev);
if (f1002dlr.getExpanded()) {
f1002dlr.setExpanded(!f1002dlr.getExpanded());
notifyItemChanged(prev);
}
}
expandedPosition = getAdapterPosition();
f1002dlr = f1002dlrList.get(expandedPosition);
f1002dlr.setExpanded(!f1002dlr.getExpanded());
updateF1002dlh();
notifyItemChanged(expandedPosition);
}
});
}
private void initAdapterViews() {
f1002dlr_status_imageView = (ImageView) itemView.findViewById(R.id.cdlItem_status_imageView);
f1002dlr_vpd_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_vpd_textView);
f1002dlr_radek_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_radek_textView);
f1002dlr_komodita_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_komodita_textView);
f1002dlr_xvyr_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_xvyr_textView);
f1002dlr_jakost_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_jakost_textView);
f1002dlr_mnozstvi_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_mnozstvi_textView);
f1002dlr_vady_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_vady_textView);
f1002dlr_mj_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_mj_textView);
f1002dlr_hodnota_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_hodnota_textView);
f1002dlr_pc_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_pc_textView);
nasnimane_mnozstvi_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_nasnimane_mnozstvi_textView);
nasnimane_vady_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_nasnimane_vady_textView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.menuItem_linearLayout);
main_constrainLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlItem_main_constraintLayout);
expandable_constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlItem_expandable_constraintLayout);
second_constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlItem_second_constraintLayout);
cdlItem_sub_recyclerView = (RecyclerView) itemView.findViewById(R.id.cdlItem_sub_recyclerView);
}
}
}
Child Adapter
public class CdlSubAdapter extends RecyclerView.Adapter<CdlSubAdapter.ViewHolder> {
private List<F1002ck_data> f1002ck_dataList;
private Context context;
private Integer showingButtonsPosition = -1;
public CdlSubAdapter(List<F1002ck_data> f1002ck_dataList, Context context) {
this.context = context;
this.f1002ck_dataList = f1002ck_dataList;
}
#NonNull
#Override
public CdlSubAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View cdSublView = inflater.inflate(R.layout.cdl_sub_item, parent, false);
return new ViewHolder(cdSublView);
}
#Override
public void onBindViewHolder(#NonNull CdlSubAdapter.ViewHolder holder, int position) {
F1002ck_data f1002ck_data = f1002ck_dataList.get(position);
ImageView f1002ck_data_status_imageView = holder.f1002ck_data_status_imageView;
if (!Objects.equals(f1002ck_data.getF1002ck_data_indikace(), Funkce.INDIKACE_OK)) {
f1002ck_data.setStatus(Funkce.STATUS_WRONG);
}
f1002ck_data_status_imageView.setImageResource(getImageId(f1002ck_data.getStatus()));
ConstraintLayout cdlSubItem_chyba_constrainLayout = holder.cdlSubItem_chyba_constrainLayout;
TextView nazev_zbozi = holder.nazev_zbozi;
TextView f1002ck_data_id_zbozi = holder.f1002ck_data_id_zbozi;
TextView f1002ck_data_cislodokl = holder.f1002ck_data_cislodokl;
TextView f1002ck_data_mnozstvi_mj1 = holder.f1002ck_data_mnozstvi_mj1;
TextView f1002ck_data_vady = holder.f1002ck_data_vady;
TextView chyba = holder.chyba;
nazev_zbozi.setText(f1002ck_data.getNazevZbozi());
f1002ck_data_id_zbozi.setText(f1002ck_data.getF1002ck_data_id_f10zbozi().toString());
f1002ck_data_cislodokl.setText(f1002ck_data.getF1002ck_data_cislodokl().toString());
f1002ck_data_mnozstvi_mj1.setText(String.format("%.2f", f1002ck_data.getF1002ck_data_mnozstvi_mj1()));
f1002ck_data_vady.setText(f1002ck_data.getF1002ck_data_vady().toString());
chyba.setText(f1002ck_data.getF1002ck_data_chyba());
LinearLayout buttons_linearLayout = holder.buttons_linearLayout;
if (showingButtonsPosition == -1) {
f1002ck_data.setShowButtons((short) View.GONE);
}
if (f1002ck_data.getShowButtons() == View.VISIBLE) {
cdlSubItem_chyba_constrainLayout.setVisibility(View.GONE);
buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
} else {
cdlSubItem_chyba_constrainLayout.setVisibility(View.VISIBLE);
buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
}
}
private int getImageId(int status) {
Integer imageId = 0;
switch (status) {
case -2:
imageId = R.drawable.orange_status;
break;
case -1:
imageId = R.drawable.red_status;
break;
case 0:
imageId = R.drawable.grey_status;
break;
case 1:
imageId = R.drawable.green_status;
break;
}
return imageId;
}
private Integer sortElementsInList(F1002ck_data f1002ck_data) {
Collections.sort(f1002ck_dataList, new Comparator<F1002ck_data>() {
#Override
public int compare(F1002ck_data t1, F1002ck_data t2) {
if (t1.getStatus().compareTo(t2.getStatus()) == 0) {
return t1.getF1002ck_data_id_f10zbozi().compareTo(t2.getF1002ck_data_id_f10zbozi());
}
return t1.getStatus().compareTo(t2.getStatus());
}
});
for (int i = 0; i < f1002ck_dataList.size(); i++) {
if (f1002ck_data.equals(f1002ck_dataList.get(i))) {
return i;
}
}
return 0;
}
private void updateF1002dlh() {
if (context instanceof AdapterCallInterface) {
((AdapterCallInterface) context).setF1002ck_data(f1002ck_dataList);
}
}
private void removeRowF1002ck_data(F1002ck_data f1002ck_data) {
if (context instanceof AdapterCallInterface) {
((AdapterCallInterface) context).removeRowF1002ck_data(f1002ck_data);
}
}
#Override
public void onViewAttachedToWindow(#NonNull ViewHolder holder) {
super.onViewAttachedToWindow(holder);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
}
#Override
public int getItemCount() {
return f1002ck_dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private ImageView f1002ck_data_status_imageView;
private ConstraintLayout cdlSubItem_chyba_constrainLayout;
private TextView nazev_zbozi;
private TextView f1002ck_data_id_zbozi;
private TextView f1002ck_data_cislodokl;
private TextView f1002ck_data_mnozstvi_mj1;
private TextView f1002ck_data_vady;
private TextView chyba;
private LinearLayout buttons_linearLayout;
private CardView edit_imageButton;
private CardView remove_imageButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
initAdapterViews();
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
F1002ck_data f1002ck_data = null;
if (showingButtonsPosition >= 0 && showingButtonsPosition != getAdapterPosition()) {
int prev = showingButtonsPosition;
f1002ck_data = f1002ck_dataList.get(prev);
if (f1002ck_data.getShowButtons() == (short) View.VISIBLE) {
f1002ck_data.setShowButtons((short) View.GONE);
notifyItemChanged(prev);
}
}
showingButtonsPosition = getAdapterPosition();
if (!f1002ck_dataList.isEmpty()) {
f1002ck_data = f1002ck_dataList.get(showingButtonsPosition);
}
if (f1002ck_data != null) {
if (f1002ck_data.getShowButtons() == (short) View.VISIBLE) {
f1002ck_data.setShowButtons((short) View.GONE);
//cdlSubItem_chyba_constrainLayout.setVisibility(View.GONE);
//buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
} else {
f1002ck_data.setShowButtons((short) View.VISIBLE);
//cdlSubItem_chyba_constrainLayout.setVisibility(View.VISIBLE);
//buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
}
}
notifyItemChanged(showingButtonsPosition);
}
});
edit_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
F1002ck_data f1002ck_data = f1002ck_dataList.get(position);
f1002ck_data.setStatus(Funkce.STATUS_OK);
f1002ck_data_status_imageView.setImageResource(getImageId(f1002ck_data.getStatus()));
showingButtonsPosition = sortElementsInList(f1002ck_data);
updateF1002dlh();
notifyDataSetChanged();
}
});
remove_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
F1002ck_data f1002ck_data = f1002ck_dataList.get(position);
f1002ck_dataList.remove(f1002ck_data);
removeRowF1002ck_data(f1002ck_data);
notifyItemRemoved(position);
}
});
}
private void initAdapterViews() {
linearLayout = (LinearLayout) itemView.findViewById(R.id.cdlSubItem_linearLayout);
f1002ck_data_status_imageView = (ImageView) itemView.findViewById(R.id.cdlSubItem_status_imageView);
cdlSubItem_chyba_constrainLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlSubItem_chyba_constraintLayout);
nazev_zbozi = (TextView) itemView.findViewById(R.id.cdlSubItem_value_nazev_zbozi_textView);
f1002ck_data_id_zbozi = (TextView) itemView.findViewById(R.id.cdlSubItem_value_id_f10zbozi_textView);
f1002ck_data_cislodokl = (TextView) itemView.findViewById(R.id.cdlSubItem_value_cislodokl_textView);
f1002ck_data_mnozstvi_mj1 = (TextView) itemView.findViewById(R.id.cdlSubItem_value_mnozstvi_mj1_textView);
f1002ck_data_vady = (TextView) itemView.findViewById(R.id.cdlSubItem_value_vady_textView);
chyba = (TextView) itemView.findViewById(R.id.cdlSubItem_value_chyba_textView);
buttons_linearLayout = (LinearLayout) itemView.findViewById(R.id.cdlSubItem_buttons_linearLayout);
edit_imageButton = (CardView) itemView.findViewById(R.id.cdlSubItem_edit_cardView);
remove_imageButton = (CardView) itemView.findViewById(R.id.cdlSubItem_remove_cardView);
}
}
}
Updated
In the course of this question, I made several changes inside the child adapter.

Where to manipulate the data in Recyclerview Adapter (Android)

My datetime is currently stored as UNIX time stamp. I want to display it as h:mm a in my Recyclerview.
Where should I convert the UNIX time stamp into normal time in the RecyclerView Adapter/Viewholder (in terms of the best performance)?
Should I do it in the getItemViewType(int position) of the RecyclerView.Adapter, or the onBindViewHolder or the bind function of the ViewHolder class?
Edit: My code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
long unixTime= current.getUnixTime();
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("h:mm a");
String formattedTime = sdf.format(time);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, formattedTime, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, formattedTime, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
This is method correct? I formatted the date in the onBindViewHoldermethod
It depends whether you want to display different dates on different items of the recyclerview, or the same date on all items of the recyclerview.
If you want to show same date to all items, better to do it outside of the adapter and then pass the parsed date to the recyclerview adapter.
Or, if you want to show different dates on each item, you should do it inside onBindViewHolder as it has access to the item position.
Remember, getItemViewType is used for getting a view type out of the available ones. This is used in case you are inflating multiple views. Think of a chatapp where view1 will display message on the left, and view2 will display message on the right; all within the same recyclerview.
The onBindViewHolder method simply performs a generic binding task. Binds what : the item of the inflated view and the data.
It seems like business logic. So, i recommend to move you UNIX time stamp convertation in Model for example.
class Chat {
private Long unixTime;
// another code
public Long getUnixTime() {
return unixTime;
}
public String convertedUnixTimeToString(String format) {
// Also need to add some format validation
if(format == null) {
// do some action, like trowing exception, or setting default value in format
}
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
return sdf.format(time);
}
}
I recommend you to use JodaTime for date&time formatting. Very useful thing.
And then, just modify your code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
You should be updating the UI changes in onBindViewHolder method. You can call bind method of ViewHolder in onBindViewHolder.
Example:
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ViewHolder> {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.sample_view, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.bind(i);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
void bind(int position) {
// Do your data updates here.
}
}
}
Just Use SimpleDateFormat with yyyy-MM-dd pattern .
Apply SimpleDateFormat.format(millis) in onBindViewHolder method of RecyclerView.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
then first you need to convert UNIX timestamp to datetime format
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
then you want to store this data to field value of RecyclerView
then you can format it from this time format like h:mm

attempting to use incompatible return type

Can someone help me with this error that I keep getting? The program that I'm trying to implement admob banner ad between items in recyclerview. every thing is ok but still this one error that blocked me from go on.
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder> {
public static final String TAG = RecipeAdapter.class.getSimpleName();
public static final HashMap<String, Integer> LABEL_COLORS = new HashMap<String, Integer>() {{
put("Low-Carb", R.color.colorLowCarb);
put("Low-Fat", R.color.colorLowFat);
put("Low-Sodium", R.color.colorLowSodium);
put("Medium-Carb", R.color.colorMediumCarb);
put("Vegetarian", R.color.colorVegetarian);
put("Balanced", R.color.colorBalanced);
}};
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Recipe> mDataSource;
private static final int DEFAULT_VIEW_TYPE = 1;
private static final int NATIVE_AD_VIEW_TYPE = 2;
public RecipeAdapter(Context context, ArrayList<Recipe> items) {
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); }
#Override public int getItemViewType(int position) {
// Change the position of the ad displayed here. Current is after 5
if ((position + 1) % 6 == 0) {
return NATIVE_AD_VIEW_TYPE;
}
return DEFAULT_VIEW_TYPE; }
#NonNull
#Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
switch (viewType) {
default:
view = layoutInflater
.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolder(view);
case NATIVE_AD_VIEW_TYPE:
view = layoutInflater.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolderAdMob(view);
}
}
#Override public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Get relevant subviews of row view
TextView titleTextView = holder.titleTextView;
TextView subtitleTextView = holder.subtitleTextView;
TextView detailTextView = holder.detailTextView;
ImageView thumbnailImageView = holder.thumbnailImageView;
//Get corresponding recipe for row final Recipe recipe = (Recipe) getItem(position);
// Update row view's textviews to display recipe information
titleTextView.setText(recipe.title);
subtitleTextView.setText(recipe.description);
detailTextView.setText(recipe.label);
// Use Picasso to load the image. Temporarily have a placeholder in case it's slow to load
Picasso.with(mContext).load(recipe.imageUrl).placeholder(R.mipmap
.ic_launcher).into(thumbnailImageView);
holder.parentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent detailIntent = new Intent(mContext, RecipeDetailActivity.class);
detailIntent.putExtra("title", recipe.title);
detailIntent.putExtra("url", recipe.instructionUrl);
mContext.startActivity(detailIntent);
}
});
// Style text views
Typeface titleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-Bold.ttf");
titleTextView.setTypeface(titleTypeFace);
Typeface subtitleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-SemiBoldItalic.ttf");
subtitleTextView.setTypeface(subtitleTypeFace);
Typeface detailTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/Quicksand-Bold.otf");
detailTextView.setTypeface(detailTypeFace);
detailTextView.setTextColor(android.support.v4.content.ContextCompat.getColor(mContext, LABEL_COLORS
.get(recipe.label)));
}
#Override public int getItemCount() {
return mDataSource.size(); }
#Override public long getItemId(int position) {
return position; }
public Object getItem(int position) {
return mDataSource.get(position); }
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView titleTextView;
private TextView subtitleTextView;
private TextView detailTextView;
private ImageView thumbnailImageView; private View parentView;
public ViewHolder(#NonNull View view){
super(view);
// create a new "Holder" with subviews
this.parentView = view;
this.thumbnailImageView = (ImageView) view.findViewById(R.id.recipe_list_thumbnail);
this.titleTextView = (TextView) view.findViewById(R.id.recipe_list_title);
this.subtitleTextView = (TextView) view.findViewById(R.id.recipe_list_subtitle);
this.detailTextView = (TextView) view.findViewById(R.id.recipe_list_detail);
// hang onto this holder for future recyclage
view.setTag(this);
}
}
public class ViewHolderAdMob extends RecyclerView.ViewHolder {
private final AdView mNativeAd;
public ViewHolderAdMob(View itemView) {
super(itemView);
mNativeAd = itemView.findViewById(R.id.nativeAd);
mNativeAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLoaded");
// }
}
#Override
public void onAdClosed() {
super.onAdClosed();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdClosed");
// }
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdFailedToLoad");
// }
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLeftApplication");
// }
}
#Override
public void onAdOpened() {
super.onAdOpened();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdOpened");
// }
}
});
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("") // Remove this before publishing app
.build();
mNativeAd.loadAd(adRequest);
}
}
}
The return type needs to be whatever ViewHolder type you declared for your adapter class.
For example, from the Android RecyclerView example page:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
// ^^^^^^^^^^^^^^^^^^^^^^
// It should return this type ^
public static class MyViewHolder extends RecyclerView.ViewHolder {
// your adapter
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// Note: returns MyAdapter.MyViewHolder, not RecyclerView.ViewHolder
}
}
In your case, you have
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder>
which means your onCreateViewHolder has to return RecipeAdapter.ViewHolder not RecyclerView.ViewHolder.
There is a separate issue too, which is that you have two ViewHolder types in the same adapter. To do this, you would need to change the ViewHolder type that your RecyclerView is based on to the generic type (RecyclerView.ViewHolder).
Please review this question, it has good answers for how to do this.

How to show the contents of a list?

In my application I get some data from server and show this into my recyclerView.
I want show all of list content not show just item 0.
My adapter codes:
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> {
private ArrayList<Post> postList;
private Context context;
private ListItemClickListener itemClickListener;
public PostsAdapter(Context context, ArrayList<Post> allPostList) {
this.context = context;
postList = allPostList;
}
public void setItemClickListener(ListItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false);
return new ViewHolder(view, viewType, itemClickListener);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgPost;
private TextView tvPostTitle, tvPostCategory, tvPostDate;
private CardView mCardView;
private ListItemClickListener itemClickListener;
public ViewHolder(View itemView, int viewType, ListItemClickListener itemClickListener) {
super(itemView);
this.itemClickListener = itemClickListener;
// Find all views ids
imgPost = (ImageView) itemView.findViewById(R.id.post_img);
tvPostTitle = (TextView) itemView.findViewById(R.id.title_text);
tvPostCategory = (TextView) itemView.findViewById(R.id.post_category);
tvPostDate = (TextView) itemView.findViewById(R.id.date_text);
mCardView = (CardView) itemView.findViewById(R.id.card_view_top);
mCardView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (itemClickListener != null) {
itemClickListener.onItemClick(getLayoutPosition(), view);
}
}
}
#Override
public int getItemCount() {
return (null != postList ? postList.size() : 0);
}
#Override
public void onBindViewHolder(PostsAdapter.ViewHolder mainHolder, int position) {
final Post model = postList.get(position);
// setting data over views
String title = model.getTitle().getRendered();
mainHolder.tvPostTitle.setText(Html.fromHtml(title));
String imgUrl = null;
if (model.getEmbedded().getWpFeaturedMedias().size() > 0) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails() != null) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl() != null) {
imgUrl = model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl();
}
}
}
if (imgUrl != null) {
Glide.with(context)
.load(imgUrl)
.into(mainHolder.imgPost);
} else {
Glide.with(context)
.load(R.color.imgPlaceholder)
.into(mainHolder.imgPost);
}
String category = null;
if (model.getEmbedded().getWpTerms().size() >= 1) {
category = model.getEmbedded().getWpTerms().get(0).get(0).getName();
}
if (category == null) {
category = context.getResources().getString(R.string.default_str);
}
mainHolder.tvPostCategory.setText(Html.fromHtml(category));
mainHolder.tvPostDate.setText(model.getFormattedDate());
}
}
but in above code just show me item 0 , but I want show all of items.
how can I it?
Try this
for (int i = 0; i < model.getEmbedded().getWpTerms().size(); i++) {
for (int j=0;j<model.getEmbedded().getWpTerms().get(i).size();j++){
Log.e("DATA",model.getEmbedded().getWpTerms().get(i).get(j).getName());
}
}
String category = "";
for(int i=0; response.size();i++){
{
category = category + "," + model.getEmbedded().getWpTerms().get(i).get(i).getName();
}
If you have used recyclerview , its adapter has onBindViewHolder() method , which gives you a position variable. Use that to iterate through the list!
model.getEmbedded().getWpFeaturedMedias().get(position).getMediaDetails()

Get parent layout from custom Adapter

Could anybody explain me, how to realize?
I have an activity with listview and footer with some elements(textview).
Listview built with custom adapter. Each listview item has few elements. And my question: how can i change textview in footer, from custom adapter, when i clicking on some listview's element?
Thx a lot!
/**** My adapter ****/
public class MyListAdapter extends ArrayAdapter<Product> implements UndoAdapter {
private final Context mContext;
private HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
ArrayList<Product> products = new ArrayList<Product>();
final int INVALID_ID = -1;
LayoutInflater lInflater;
String imagePath;
public MyListAdapter(Context context, int textViewResourceId, List<Product> prod) {
//super(context, textViewResourceId, prod);
super(prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
for (int i = 0; i < prod.size(); i++) {
//add(prod.get(i));
mIdMap.put(prod.get(i),i);
}
}
#Override
public long getItemId(final int position) {
//return getItem(position).hashCode();
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;;
Product p = getItem(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.item, null);
//convertView.setBackgroundResource(R.drawable.rounded_corners);
int currentTheme = Utils.getCurrentTheme(convertView.getContext());
switch (currentTheme) {
case 0:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
case 1:
convertView.setBackgroundResource(R.drawable.border);
break;
default:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
}
holder = new ViewHolder();
holder.tvDescr = (TextView) convertView.findViewById(R.id.tvDescr);
holder.list_image = (ImageView) convertView.findViewById(R.id.list_image);
holder.products_amount = (TextView) convertView.findViewById(R.id.amountDigits);
holder.products_price = (TextView) convertView.findViewById(R.id.priceDigits);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
holder.unit = (TextView) convertView.findViewById(R.id.unit);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(p.getProductImageBitmap() != null && p.getProductImageBitmap() != "") {
Log.d("PATH -- ", p.getProductImageBitmap());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
/*.showImageOnLoading(R.id.progress_circular)*/
.build();
imageLoader.displayImage(p.getProductImageBitmap(), holder.list_image, options);
} else {
holder.list_image.setImageResource(R.drawable.ic_launcher);
}
holder.tvDescr.setText(p.getProductName());
holder.ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String deletedItem = getItem(position).getProductName();
MyListAdapter.this.remove(getItem(position));
if (MyListAdapter.this.getCount() > 0) {
Toast.makeText(mContext, deletedItem + " " + mContext.getString(R.string.deleted_item), Toast.LENGTH_SHORT).show();
MyListAdapter.this.notifyDataSetChanged();
} else {
Toast.makeText(mContext,mContext.getString(R.string.sklerolist_empty), Toast.LENGTH_SHORT).show();
}
}
});
//Функционал для большой картинки продукта
//открывается новое активити с большой картинкой
holder.list_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePath = getItem(position).getProductImageBitmap();
if(imagePath != null && imagePath != "") {
Pattern normalPrice = Pattern.compile("^file");
Matcher m2 = normalPrice.matcher(imagePath);
if (m2.find()) {
Intent myIntent = new Intent(view.getContext(), ViewImage.class).putExtra("imagePath", imagePath);
view.getContext().startActivity(myIntent);
}
}
}
});
holder.products_price.setText(fmt(p.getProductPrice()));
holder.products_amount.setText(fmt(p.getProductAmount()));
holder.unit.setText(p.getProductUnit());
return convertView;
}
public static String fmt(double d){
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
static class ViewHolder {
ImageView list_image;
TextView tvDescr;
TextView products_amount;
TextView products_price;
TextView unit;
ImageView ivImage;
ProgressBar circleProgress;
}
#NonNull
#Override
public View getUndoView(final int position, final View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
if (view == null) {
//view = LayoutInflater.from(mContext).inflate(R.layout.undo_row, parent, false);
view = lInflater.inflate(R.layout.undo_row, parent, false);
}
return view;
}
#NonNull
#Override
public View getUndoClickView(#NonNull final View view) {
return view.findViewById(R.id.undo_row_undobutton);
}
public View getHeaderView(final int position, final View convertView, final ViewGroup parent) {
TextView view = (TextView) convertView;
//View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_header, parent, false);
//view = lInflater.inflate(R.layout.list_header, parent, false);
}
//view.setText(mContext.getString(R.string.header, getHeaderId(position)));
return view;
}
public long getHeaderId(final int position) {
return position / 10;
}
}
Your ListView has a listener for the click events on list elements.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something when a list item is clicked
}
But if you want to pas something else back from the adapter to the Activity or the Fragment that contains that ListView and Adapter, you should create a simple interface and set it as listener to your adapter. After that, set click events on your rows from within the adapter, and notify the Activity or Fragment using your own interface.
For example you have the interface defined like this
public interface OnItemClickedCustomAdapter {
public void onClick(ItemPosition position);
}
and in your Adapter class you will have a private member
private OnItemClickedCustomAdapter mListener;
and a method used to set the listener
public void setOnItemClickedCustomAdapter(OnItemClickedCustomAdapter listener){
this.mListener = listener;
}
From your Activity or Fragment where your ListView is defined, and your adapter is set, you will be able to call setOnItemClickedCustomAdapter with this as parameter, and there you go. Your activity will now listen for your events. To trigger an event, just call mListener.onClick() from your custom adapter. You can pass back data you need back to the Activity or Fragment, and from there you have access to your Header or Footer directly, and you can change the text on them.

Categories

Resources