Recyclerview item height changing when I do scroll up and down continuously - android

In one of my applications I am trying to use recyclerview to display content. My content would be like chat history(it may be a single line text or multiple lines text).To implement this I have used recyclerview with Textview height as wrap_content to adjust the height based on the content. For the first time it is loading fine. But when I do scroll up and down I am getting some extra white space for some of the items. (I strongly suspect this extra space is for earlier item height).
Ex: I have a recyclerview list having 1,2,3,4,5.. lines text in each row. When I do scroll up down continuously I am getting row/item height is changing like 1 line text item got 5 lines text space and 5 lines text item got 1 line text.
Please find my adapter code below.
public class ConversationMessagesAdapterNew extends RecyclerView.Adapter {
private ConversationDetailActivityNew context;
private LayoutInflater layoutInflater;
private Utils utils;
private List<Message> messages = null;
private SessionManagement mSessionManage;
private int loginId = 0, attachmentsCount = 0, gifCount = 0;
private String mProfilePicId, mFname, mLname, fname = "", lname = "";
private ComposeDetails composeDetails;
private JSONArray attachmentArrayObj = new JSONArray();
public ConversationMessagesAdapterNew(ConversationDetailActivityNew context) {
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.utils = new Utils(context);
setHasStableIds(true);
this.mSessionManage = new SessionManagement(context, Utils.SHARED_PREF);
loginId = Integer.parseInt(mSessionManage.getString("userId"));
this.mProfilePicId = mSessionManage.getString("profilePicId");
this.mFname = mSessionManage.getString("firstName");
this.mLname = mSessionManage.getString("lastName");
}
public void setMessages(List<Message> messagesList) {
this.messages = messagesList;
/*if (messagesList == null) {
if (this.messages != null) {
this.messages.clear();
this.messages = null;
}
} else {
if (this.messages != null && this.messages.size() > 0)
this.messages.addAll(messagesList);
else
this.messages = messagesList;
}*/
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.conversation_messages_list_row_item_longpress, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final ViewHolder messagesListViewHolder = (ViewHolder) holder;
Message message = messages.get(position);
messagesListViewHolder.mMainLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
(context).loadMoreButtonlayout(message);
return true;
}
});
try {
String picId = "";
composeDetails = (context).getProfilePicId(String.valueOf(message.getSenderId()));
if (composeDetails != null) {
fname = composeDetails.getFristName();
lname = composeDetails.getLastName();
}
if (message.getSenderId() == loginId) {
picId = mProfilePicId;
} else {
//picId = ((ConversationDetailActivity)context).getProfilePicId(String.valueOf(message.getSenderId()));
if (composeDetails != null) {
picId = composeDetails.getProfilePicture();
fname = composeDetails.getFristName();
lname = composeDetails.getLastName();
}
mFname = fname;
mLname = lname;
}
if (!picId.equals("null")) {
messagesListViewHolder.iv_user_profile.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_lettersText.setVisibility(View.GONE);
messagesListViewHolder.mCardView.setCardBackgroundColor(Color.parseColor("#EFEFEF"));
String url = String.format("%s%s", Constants.mDisplayProfilePicUrl, picId);
Picasso.with(context).load(url).placeholder(R.drawable.user_default).into(messagesListViewHolder.iv_user_profile);
} else {
messagesListViewHolder.iv_user_profile.setVisibility(View.GONE);
messagesListViewHolder.tv_lettersText.setVisibility(View.VISIBLE);
messagesListViewHolder.mCardView.setCardBackgroundColor(Color.parseColor("#77B633"));
String name = getName(mFname, mLname);
messagesListViewHolder.tv_lettersText.setText(name);
}
if (message.getMessageType().equals("OFFNETEMAIL")) {
messagesListViewHolder.tv_sender_name.setTextColor(Color.parseColor("#2C303E"));
} else {
messagesListViewHolder.tv_sender_name.setTextColor(Color.parseColor("#276eb6"));
}
String sendName = message.getSenderName();
if (message.getMetric().getFlags().getCount() > 0 ||
message.getMetric().getLikes().getCount() > 0) {
if (sendName.length() > 15) {
sendName = sendName.substring(0, 15) + "..";
}
} else {
if (sendName.length() > 18) {
sendName = sendName.substring(0, 18) + "..";
}
}
messagesListViewHolder.tv_sender_name.setText(sendName);
messagesListViewHolder.tv_created_time.setText(utils.getTimeStampByString(message.getCreatedOn()));
String content = message.getContent();
// Attachment parsing
String prtnAttachment = "\\<attachment:(.*?)\\>";
Pattern ptr = Pattern.compile(prtnAttachment);
Matcher m = ptr.matcher(content);
while (m.find()) {
String[] fileStr = m.group(0).toString().split(":");
if (fileStr.length > 0) {
JSONObject file = new JSONObject();
file.put("fileId", fileStr[1].toString());
file.put("fileName", fileStr[2].toString());
file.put("fileType", fileStr[3].toString());
file.put("randomFileName", fileStr[4].toString());
file.put("fileSize", fileStr[5].toString());
attachmentArrayObj.put(file);
attachmentsCount++;
} else {
//attachmentsFlag = false;
// imageFlag = false;
attachmentsCount = 0;
}
}
// Emoji / Mentions parsing
String ptrsEmoji = "\\<:(.*?)\\>";
Pattern ptrEmoji = Pattern.compile(ptrsEmoji);
Matcher em = ptrEmoji.matcher(content);
while (em.find()) {
String[] emojiStr = em.group(0).split(":");
if (emojiStr.length > 0) {
if (emojiStr[1].contains("mention-everyone")) {
String parsedStr = "<font color='#1F6EB7'>" + "#everyone" + "</font>";
content = content.replaceAll(em.group(0), parsedStr);
} else if (emojiStr[1].contains("mention-")) {
String[] ms = emojiStr[1].split("-");
String parsedStr = "<font color='#1F6EB7'>" + "#" + ms[1] + "</font>";
content = content.replaceAll(em.group(0), parsedStr);
} else {
String parsedStr = "&#x" + emojiStr[1];
content = content.replaceAll(em.group(0), parsedStr);
}
}
}
if (content.length() > 0) {
messagesListViewHolder.tv_message.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_message.setText(Html.fromHtml(content));
} else {
messagesListViewHolder.tv_message.setVisibility(View.GONE);
}
if (attachmentsCount > 0) {
messagesListViewHolder.tv_message.setVisibility(View.GONE);
messagesListViewHolder.mAttachLayout.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_attachments.setText(String.valueOf(attachmentsCount + gifCount) + " Attachments.");
attachmentsCount = 0;
} else {
attachmentsCount = 0;
messagesListViewHolder.tv_message.setVisibility(View.VISIBLE);
messagesListViewHolder.mAttachLayout.setVisibility(View.GONE);
}
// Likes and Flag sectin
if (message.getMetric().getLikes().getCount() > 0) {
messagesListViewHolder.iv_likes_icon.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_likes_count.setVisibility(View.VISIBLE);
messagesListViewHolder.tv_likes_count.setText(String.valueOf(message.getMetric().getLikes().getCount()));
} else {
messagesListViewHolder.iv_likes_icon.setVisibility(View.GONE);
messagesListViewHolder.tv_likes_count.setVisibility(View.GONE);
}
if (message.getMetric().getFlags().getCount() > 0) {
messagesListViewHolder.iv_flag_icon.setVisibility(View.VISIBLE);
} else {
messagesListViewHolder.iv_flag_icon.setVisibility(View.GONE);
}
messagesListViewHolder.mAttachLayout.setOnClickListener(v -> {
Intent attachmentIntent = new Intent(context, AttachmentsView.class);
attachmentIntent.putExtra("contentAttachment", message.getContent());
context.startActivity(attachmentIntent);
});
messagesListViewHolder.mAttachLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
(context).loadMoreButtonlayout(message);
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
if (messages != null && messages.size() > 0)
return messages.size();
else
return 0;
}
#Override
public long getItemId(int position) {
Message message = messages.get(position);
return message.getId();
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout mMainLayout;
ImageView iv_user_profile, iv_likes_icon, iv_flag_icon;
TextView tv_sender_name, tv_created_time, tv_message, tv_lettersText, tv_attachments, tv_likes_count;
CardView mCardView;
FrameLayout mMoreLayout;
RelativeLayout mAttachLayout;
View mDummyLongPressLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mMainLayout = itemView.findViewById(R.id.longpress_layout_detailpage);
mDummyLongPressLayout = itemView.findViewById(R.id.DummyLongPressLayout);
mMoreLayout = itemView.findViewById(R.id.delete_layout);
iv_user_profile = itemView.findViewById(R.id.iv_user_profile);
tv_sender_name = itemView.findViewById(R.id.tv_sender_name);
tv_sender_name.setTypeface(utils.mRobotoBold);
tv_created_time = itemView.findViewById(R.id.tv_created_time);
tv_created_time.setTypeface(utils.mRobotoRegular);
tv_message = itemView.findViewById(R.id.tv_message);
tv_message.setTypeface(utils.mRobotoRegular);
tv_lettersText = itemView.findViewById(R.id.tv_lettersText);
tv_lettersText.setTypeface(utils.mRobotoRegular);
mCardView = itemView.findViewById(R.id.card_view);
mAttachLayout = itemView.findViewById(R.id.AttachmentsLayout);
mAttachLayout.setVisibility(View.GONE);
tv_attachments = itemView.findViewById(R.id.tv_attachments);
tv_likes_count = itemView.findViewById(R.id.tv_likes_count);
iv_likes_icon = itemView.findViewById(R.id.iv_like_icon);
iv_flag_icon = itemView.findViewById(R.id.iv_flag_icon);
}
}
private String getName(String fname, String lname) {
if (fname.length() > 0) {
if (!fname.equals("null")) {
fname = fname.substring(0, 1).toUpperCase();
} else {
fname = "";
}
} else {
fname = "";
}
if (lname.length() > 0) {
if (!lname.equals("null")) {
lname = lname.substring(0, 1).toUpperCase();
} else {
lname = "";
}
} else {
lname = "";
}
return fname + lname;
}
}

Related

Android checkbox checked at random position in Listview

I know it is common problem with Listview and Checkbox, I am try from 2 days but it is not solving, so I raised question here.
I had list of items in Arraylist, like 15(supposed) items. Inside listview there is a checkbox, by default 11(supposed) checkbox is comes checked by API (JSON Response)
But I have to show only 5 items checked. I tried alot but not find any solution.
I had create a dummy list that contain 11 items that comes from API and save 5 items from original arraylist. Here is code to match items in listview and save this list in Shared Preference.
Adapter class inside getViwe() function
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
for (int i = 0; i < getIds.size(); i++) {
String idget = getIds.get(i).getOrderId();// it get ids from save list
for (int j = 0; j < newOrders.size(); j++) {
String bot = newOrders.get(j).getId(); // id from orginal list
if (bot.equalsIgnoreCase(idget)) {
showErrorLog(TAG, String.format("Bot id is %s and Saved Id is %s", bot, idget));
myViewHolder.add_payment.setChecked(true);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
myViewHolder.txt_check_status.setText("ADDED");
} else {
getPerspective().showErrorLog(TAG, "Not Equal");
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
}
}
}
Adapter class code is here
public class NewOrderAdapter extends BaseAdapter {
private String TAG = "Current Order";
private Context context;
private List<NewOrder> newOrders;
private MyOrders myOrders;
private Perspective perspective;
private double total = 0.0;
private PrefManager prefManager;
// private List<SaveOrderId> ids;
private boolean isAdded = false;
private List<SaveOrderId> papa = new ArrayList<>();
private LayoutInflater inflater;
public NewOrderAdapter(Context context, List<NewOrder> newOrders, MyOrders myOrders) {
this.context = context;
this.newOrders = newOrders;
this.myOrders = myOrders;
prefManager = new PrefManager(this.context);
total = myOrders.total;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ids = new ArrayList<>();
}
private void showDeleteAlert(final String orderId) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle("Alert");
builder1.setMessage(context.getString(R.string.delete_order));
builder1.setCancelable(false);
builder1.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
myOrders.cancelOrder(orderId);
}
});
builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
public int getCount() {
return newOrders.size();
}
#Override
public Object getItem(int position) {
return newOrders.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder myViewHolder;
if (convertView == null) {
myViewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_new_order_row, parent, false);
myViewHolder.img_delete = (ImageView) convertView.findViewById(R.id.img_delete);
myViewHolder.add_payment = (CheckBox) convertView.findViewById(R.id.add_payment);
myViewHolder.txt_topic_name = (TextView) convertView.findViewById(R.id.txt_topic_name);
myViewHolder.txt_order_id = (TextView) convertView.findViewById(R.id.txt_order_id);
myViewHolder.txt_delivery_date = (TextView) convertView.findViewById(R.id.txt_delivery_date);
myViewHolder.txt_words = (TextView) convertView.findViewById(R.id.txt_words);
myViewHolder.txt_order_status = (TextView) convertView.findViewById(R.id.txt_order_status);
myViewHolder.txt_offer_price = (TextView) convertView.findViewById(R.id.txt_offer_price);
myViewHolder.txt_price_tag = (TextView) convertView.findViewById(R.id.txt_price_tag);
myViewHolder.txt_check_status = (TextView) convertView.findViewById(R.id.txt_check_status);
myViewHolder.txt_total_amount = (TextView) convertView.findViewById(R.id.txt_total_amount);
myViewHolder.txt_payment_status = (TextView) convertView.findViewById(R.id.txt_payment_status);
myViewHolder.txt_paid_amount = (TextView) convertView.findViewById(R.id.txt_paid_amount);
myViewHolder.txt_view_more = (TextView) convertView.findViewById(R.id.txt_view_more);
myViewHolder.txt_order_tag = (TextView) convertView.findViewById(R.id.txt_order_tag);
myViewHolder.txt_layout_checked = (RelativeLayout) convertView.findViewById(R.id.txt_layout_checked);
myViewHolder.layout_payment_details = (RelativeLayout) convertView.findViewById(R.id.layout_payment_details);
myViewHolder.layout_paid = (LinearLayout) convertView.findViewById(R.id.layout_paid);
convertView.setTag(myViewHolder);
} else {
myViewHolder = (ViewHolder) convertView.getTag();
}
try {
myViewHolder.txt_topic_name.setText(newOrders.get(position).getTopic());
if (newOrders.get(position).getOrder_code().equalsIgnoreCase("Not allotted")
|| newOrders.get(position).getOrder_code().equalsIgnoreCase("")) {
myViewHolder.txt_order_tag.setText(context.getString(R.string.temp_id));
myViewHolder.txt_order_id.setText(newOrders.get(position).getId());
} else {
myViewHolder.txt_order_tag.setText(context.getText(R.string.order_code_));
myViewHolder.txt_order_id.setText(newOrders.get(position).getOrder_code());
}
myViewHolder.txt_words.setText(String.format("%s Words", newOrders.get(position).getWords()));
myViewHolder.txt_order_status.setText(newOrders.get(position).getProject_status());
myViewHolder.txt_offer_price.setText(String.format("%s %s %s", newOrders.get(position).getPrice_label(), newOrders.get(position).getSymbol(), newOrders.get(position).getDue()));
myViewHolder.txt_price_tag.setText(newOrders.get(position).getPayment_label());
myViewHolder.txt_total_amount.setText(String.format("%s %s", newOrders.get(position).getSymbol(), newOrders.get(position).getCost()));
String projectStatus = newOrders.get(position).getProject_status();
if (projectStatus.equalsIgnoreCase("in process")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (projectStatus.equalsIgnoreCase("delivered")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.green_text));
} else if (projectStatus.equalsIgnoreCase("pending")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.red));
} else if (projectStatus.equalsIgnoreCase("feedback")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.feedback));
} else if (projectStatus.equalsIgnoreCase("checked")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.checked));
} else if (projectStatus.equalsIgnoreCase("ready")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.ready));
} else if (projectStatus.equalsIgnoreCase("delivered draft")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.delivered_draft));
} else if (projectStatus.equalsIgnoreCase("Payment Refund")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.payment_refund));
} else if (projectStatus.equalsIgnoreCase("Not Accepted")) {
myViewHolder.txt_order_status.setTextColor(ContextCompat.getColor(context, R.color.black));
}
String payStatus = newOrders.get(position).getPay_status();
if (payStatus.equalsIgnoreCase("Pending")) {
myViewHolder.txt_payment_status.setText(payStatus);
myViewHolder.txt_payment_status.setTextColor(context.getResources().getColor(R.color.red));
}
if (payStatus.equalsIgnoreCase("Partially paid")) {
myViewHolder.txt_payment_status.setText(payStatus);
myViewHolder.txt_payment_status.setTextColor(context.getResources().getColor(R.color.orange));
}
if (payStatus.equalsIgnoreCase("Complete")) {
myViewHolder.txt_payment_status.setText(payStatus);
myViewHolder.txt_payment_status.setTextColor(context.getResources().getColor(R.color.green_text));
}
double paidAmt = newOrders.get(position).getPaid();
if (paidAmt == 0) {
myViewHolder.layout_paid.setVisibility(View.GONE);
} else {
myViewHolder.layout_paid.setVisibility(View.VISIBLE);
myViewHolder.txt_paid_amount.setText(String.format("%s %s", newOrders.get(position).getSymbol(), newOrders.get(position).getPaid()));
}
final String gateway_name = newOrders.get(position).getPayment_gateway_name();
myViewHolder.add_payment.setEnabled(false);
if (gateway_name.equalsIgnoreCase(prefManager.getCurrencyGateway())) {
if (!newOrders.get(position).getPay_status().equalsIgnoreCase("Complete")) {
double dueAmt = newOrders.get(position).getDue();
myViewHolder.layout_payment_details.setVisibility(View.VISIBLE);
if (dueAmt != 0) {
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
for (int i = 0; i < getIds.size(); i++) {
String idget = getIds.get(i).getOrderId();
for (int j = 0; j < newOrders.size(); j++) {
String bhoot = newOrders.get(j).getId();
if (bhoot.equalsIgnoreCase(idget)) {
showErrorLog(TAG, String.format("Bhoot id is %s and Saved Id is %s", bhoot, idget));
myViewHolder.add_payment.setChecked(true);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
myViewHolder.txt_check_status.setText("ADDED");
} else {
showErrorLog(TAG, "Not Equal");
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
}
}
}
}
} else {
myViewHolder.layout_payment_details.setVisibility(View.GONE);
}
} else {
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
}
// prefManager.saveNewOrders(context, ids);
myViewHolder.txt_layout_checked.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// myViewHolder.add_payment.performClick();
double dueAmt = newOrders.get(position).getDue();
if (dueAmt == 0.00) {
showErrorLog("Adapter", "No Order");
myViewHolder.add_payment.setChecked(false);
showAlert(context.getString(R.string.alert_header_warning), context.getString(R.string.alert_3_msg), "Ok");
} else {
if (!myViewHolder.add_payment.isChecked()) {
int size = prefManager.getNewOrders(context).size();
if (size < 6) {
String dis = newOrders.get(position).getId().concat(newOrders.get(position).getTopic());
if (size == 0) {
String orderid = newOrders.get(position).getId();
String payName = newOrders.get(position).getPayment_gateway_name();
SaveOrderId saveOrderId = new SaveOrderId(orderid, payName);
papa.add(saveOrderId);
prefManager.saveNewOrders(context, papa);
myViewHolder.add_payment.setChecked(true);
myViewHolder.txt_check_status.setText("ADDED");
String sym = newOrders.get(position).getSymbol();
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
total = total + newOrders.get(position).getDue();
myOrders.setPrice(sym, total, payName, dis);
} else {
String orderid = newOrders.get(position).getId();
String payName = newOrders.get(position).getPayment_gateway_name();
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
for (int i = 0; i < getIds.size(); i++) {
String name = getIds.get(i).getGateWayName();
if (name.equalsIgnoreCase(payName)) {
isAdded = true;
break;
} else {
isAdded = false;
}
}
if (isAdded) {
myViewHolder.txt_check_status.setText("ADDED");
String sym = newOrders.get(position).getSymbol();
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_green));
}
total = total + newOrders.get(position).getDue();
myOrders.setPrice(sym, total, payName, dis);
myViewHolder.add_payment.setChecked(true);
SaveOrderId saveOrderId = new SaveOrderId(orderid, payName);
papa.add(saveOrderId);
prefManager.saveNewOrders(context, papa);
} else {
showAlert(context.getString(R.string.alert_header_notic), context.getString(R.string.alert_1_msg), "Ok");
myViewHolder.add_payment.setChecked(false);
}
}
} else {
showMessage("Maximum limit reached.");
}
} else {
List<SaveOrderId> getIds = prefManager.getNewOrders(context);
String name = newOrders.get(position).getPayment_gateway_name();
String dis = newOrders.get(position).getId().concat(newOrders.get(position).getTopic());
if (getIds.size() != 0) {
for (int i = 0; i < getIds.size(); i++) {
String abc = getIds.get(i).getGateWayName();
if (abc.equalsIgnoreCase(name)) {
getIds.remove(i);
prefManager.saveNewOrders(context, getIds);
break;
}
}
}
if (prefManager.getNewOrders(context).size() == 0) {
papa.clear();
prefManager.clearOrderIds(context);
}
String sym = newOrders.get(position).getSymbol();
myViewHolder.txt_check_status.setText("ADD FOR PAYMENT");
myViewHolder.add_payment.setChecked(false);
final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
myViewHolder.txt_layout_checked.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
} else {
myViewHolder.txt_layout_checked.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_rect_rounder_corner3_bg_dark_gray));
}
total = total - newOrders.get(position).getDue();
myOrders.setPrice(sym, total, name, dis);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
class ViewHolder {
TextView txt_topic_name, txt_order_id, txt_delivery_date, txt_words, txt_order_status, txt_offer_price, txt_price_tag, txt_check_status,
txt_total_amount, txt_payment_status, txt_paid_amount, txt_view_more, txt_order_tag;
CheckBox add_payment;
ImageView img_delete;
RelativeLayout txt_layout_checked, layout_payment_details;
LinearLayout layout_paid;
}
}
Problem is that, all 11 items showing checked. Please help.

Items not displaying orderwise in Recycler View

In my Recycler View not displaying the item orderwise routinely changing the items for each and every time while running the program.
How to display Order wise the items in Recycler View.
Code:
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
Adapter:
public class CartlistAdapter extends RecyclerView.Adapter < CartlistAdapter.ViewHolder > {
private ArrayList < CartItemoriginal > cartlistadp;
private ArrayList < Cartitemoringinaltwo > cartlistadp2;
DisplayImageOptions options;
private Context context;
public static final String MyPREFERENCES = "MyPrefs";
public static final String MYCARTPREFERENCE = "CartPrefs";
public static final String MyCartQtyPreference = "Cartatyid";
SharedPreferences.Editor editor;
SharedPreferences shared,
wishshared;
SharedPreferences.Editor editors;
String pos,
qtyDelete;
String date;
String currentDateandTime;
private static final int VIEW_TYPE_ONE = 1;
private static final int VIEW_TYPE_TWO = 2;
private static final int TYPE_HEADER = 0;
private Double orderTotal = 0.00;
DecimalFormat df = new DecimalFormat("0");
Double extPrice;
View layout,
layouts;
SharedPreferences sharedPreferences;
SharedPreferences.Editor QutId;
boolean flag = false;
public CartlistAdapter() {
}
public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {
this.cartlistadp = cartlistadp;
this.cartlistadp2 = cartlistadp2;
this.context = context;
options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
.showImageForEmptyUri(R.drawable.b2).build();
if (YelloPage.imageLoader.isInited()) {
YelloPage.imageLoader.destroy();
}
YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
public int getItemViewType(int position) {
if (cartlistadp.size() == 0) {
Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
return VIEW_TYPE_TWO;
}
return VIEW_TYPE_ONE;
}
#Override
public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
ViewHolder viewHolder = null;
switch (position) {
case VIEW_TYPE_TWO:
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
viewHolder = new ViewHolder(view2, new MyTextWatcher(viewGroup, position));
// return view holder for your placeholder
break;
case VIEW_TYPE_ONE:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
viewHolder = new ViewHolder(view, new MyTextWatcher(view, position));
// return view holder for your normal list item
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
viewHolder.Error.setText(cartlistadp.get(position).getError());
viewHolder.qty.setTag(cartlistadp.get(position));
viewHolder.myTextWatcher.updatePosition(position);
if (cartlistadp.get(position).getQty() != 0) {
viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
viewHolder.itemView.setTag(viewHolder);
} else {
viewHolder.qty.setText("0");
}
YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
}
#Override
public int getItemCount() {
return cartlistadp.size();
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return cartlistadp.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
private ImageView cartitemimg;
private ImageButton wishbtn, removebtn;
private LinearLayout removecart, movewishlist;
private CardView cd;
private EditText qty;
private ImageView WishImg;
public MyTextWatcher myTextWatcher;
public ViewHolder(final View view, MyTextWatcher myTextWatcher) {
super(view);
productnames = (TextView) view.findViewById(R.id.cartitemname);
cartalisname = (TextView) view.findViewById(R.id.cartalias);
cartprice = (TextView) view.findViewById(R.id.CartAmt);
cartdelivery = (TextView) view.findViewById(R.id.cartdel);
cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
Error = (TextView) view.findViewById(R.id.error);
this.myTextWatcher = myTextWatcher;
removecart = (LinearLayout) view.findViewById(R.id.removecart);
movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);
WishImg = (ImageView) view.findViewById(R.id.wishimg);
qty = (EditText) view.findViewById(R.id.quantity);
qty.addTextChangedListener(myTextWatcher);
String pid, qid;
sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
QutId = sharedPreferences.edit();
Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
//MyTextWatcher textWatcher = new MyTextWatcher(view,qty);
// qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
//qty.addTextChangedListener(textWatcher);
qty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
qty.setSelection(qty.getText().length());
return false;
}
});
wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();
shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();
cd = (CardView) view.findViewById(R.id.cv);
productnames.setSingleLine(false);
productnames.setEllipsize(TextUtils.TruncateAt.END);
productnames.setMaxLines(2);
//totalPrice();
view.setClickable(true);
// view.setFocusableInTouchMode(true);
removecart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cartlistadp.size() == 1) {
Intent list = new Intent(v.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
removeAt(getAdapterPosition());
Log.i(String.valueOf(getPosition()), "item");
Toast.makeText(context, "All items deleted from your WishList", Toast.LENGTH_LONG).show();
} else {
removeAt(getAdapterPosition());
}
}
});
MovewishList();
totalPrice();
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void removeAt(int positions) {
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray item = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
String channel = shared.getString(Constants.cartid, String.valueOf(test));
pos = cartlistadp.get(getAdapterPosition()).getProductid();
qtyDelete = String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
try {
JSONArray delteitems = new JSONArray(channel);
itemsQty = delteitems.getJSONArray(0);
item = delteitems.getJSONArray(1);
for (int x = 0; x < itemsQty.length(); x++) {
if (pos.equalsIgnoreCase(itemsQty.getString(x))) {
itemsQty.remove(x);
cartlistadp.remove(positions);
notifyItemRemoved(positions);
notifyItemRangeChanged(positions, cartlistadp.size());
notifyDataSetChanged();
}
}
for (int y = 0; y < item.length(); y++) {
if (qtyDelete.equalsIgnoreCase(item.getString(y)))
item.remove(y);
}
String s = String.valueOf(delteitems);
editor.putString(Constants.cartid, String.valueOf(delteitems));
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void MovewishList() {
movewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartlistadp.size() == 1) {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
JSONArray items3;
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems1", Toast.LENGTH_LONG).show();
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Toast.makeText(context, Constants.productid, Toast.LENGTH_LONG).show();
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
} else {
removeAt(getAdapterPosition());
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
}
} else {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
removeAt(getAdapterPosition());
}
}
}
});
}
}
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private EditText editText;
private int position;
//private int position;
private MyTextWatcher(View view, int position) {
this.view = view;
this.position = position;
// this.position = adapterPosition;
// cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// EditText qtyView = (EditText) view.findViewById(R.id.quantity);
Log.i("editextpostion", String.valueOf(position));
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0");
String qtyString = s.toString();
int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
String quty = String.valueOf(quantity);
EditText qtyView = (EditText) view.findViewById(R.id.quantity);
CartItemoriginal product = (CartItemoriginal) qtyView.getTag();
// int position = (int) view.qtyView.getTag();
Log.d("postion is qtytag", "Position is: " + product);
qtyView.setFilters(new InputFilter[] {
new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
});
if (product.getQty() != quantity) {
Double currPrice = product.getExt();
Double price = Double.parseDouble(product.getPrice());
int maxaty = Integer.parseInt(product.getMaxquantity());
int minqty = Integer.parseInt(product.getMinquantity());
if (quantity < maxaty) {
extPrice = quantity * price;
} else {
Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + " " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
}
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
product.setQty(quantity);
product.setExt(extPrice);
TextView ext = (TextView) view.findViewById(R.id.CartAmt);
if (product.getQty() != 0) {
ext.setText("Rs." + " " + df.format(product.getExt()));
} else {
ext.setText("0");
}
if (product.getQty() != 0) {
qtyView.setText(String.valueOf(product.getQty()));
} else {
qtyView.setText("");
}
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray items = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
JSONArray listitems = null;
//String Sharedqty= String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
String channel = (shared.getString(Constants.cartid, String.valueOf(test)));
try {
listitems = new JSONArray(channel);
itemsQty = listitems.getJSONArray(1);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (itemsQty != null) {
itemsQty.put(position + 1, qtyString);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (listitems != null) {
listitems.put(1, itemsQty);
}
} catch (JSONException e) {
e.printStackTrace();
}
QutId.putString(Constants.cartid, String.valueOf(listitems));
QutId.apply();
Toast.makeText(context, String.valueOf(listitems), Toast.LENGTH_SHORT).show();
totalPrice();
}
return;
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void updatePosition(int position) {
this.position = position;
}
}
}
Thanks in Advance.
For sorting you need to Collection.sort method of Java and also you need to implement comparable interface for define your comparison.
CartItemoriginal implements Comparable {
public int compareTo(Object obj) { } }
Updated
public class CartItemoriginal implements Comparable<CartItemoriginal > {
private Float val;
private String id;
public CartItemoriginal (Float val, String id){
this.val = val;
this.id = id;
}
#Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
#Override
public String toString(){
return this.id;
}
}
and use
Collections.sort(sortList);

howt to solve the getview's position is cofusition in the baseadapter in android

#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder helper = null;
Log.i("StaggeredGridView--Adapter:", "position:" + position);
if(convertView ==null){
helper = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user_details_adapter, null);
helper.tv_content = (EmojiconTextView) convertView.findViewById(R.id.txt_content);
helper.tv_time = (TextView) convertView.findViewById(R.id.txt_time);
helper.tv_zannum = (TextView) convertView.findViewById(R.id.tv_zan_num);
helper.tv_plnum = (TextView) convertView.findViewById(R.id.tv_pl_num);
helper.iv_show = (DynamicHeightImageView) convertView.findViewById(R.id.img_content);// 展示的图片
helper.img_zan = (ImageView) convertView.findViewById(R.id.img_normal);// 已经赞过的改颜色。
helper.rel_photo = (RelativeLayout) convertView.findViewById(R.id.rel_photo);
convertView.setTag(helper);
} else {
helper = (ViewHolder) convertView.getTag();
}
double positionHeight = getPositionRatio(position);
Log.d(TAG, "getView position:" + position + " h:" + positionHeight);
helper.iv_show.setHeightRatio(positionHeight);
String imgeurl = "";
List<Map<String, String>> listget = mUserInfors.get(position).getmAttach();
if (listget != null && listget.size() > 0) {
for (int i = 0; i < listget.size(); i++) {
Map<String, String> map = listget.get(i);
if (map != null) {
if (map.get("attach_middle") != null) {
imgeurl = map.get("attach_middle");
if (!TextUtils.isEmpty(imgeurl)) {
break;
}
}
}
}
}
List<Map<String, String>> diggerlist = mUserInfors.get(position).getDigger_list();
if (diggerlist.size() > 0) {
helper.tv_zannum.setText(diggerlist.size() + "");
boolean state = getCheckstate(diggerlist);
if (state) {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.zan));
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
if (!TextUtils.isEmpty(imgeurl)) {
ImageLoader.getInstance().displayImage(imgeurl, helper.iv_show, mDisplayOption);
} else {
helper.iv_show.setImageDrawable(mContext.getResources().getDrawable(R.drawable.empty_activity_icon));
}
String content = mUserInfors.get(position).getContent();
String time = mUserInfors.get(position).getCtime();
helper.tv_time.setText(time.substring(5));
helper.tv_zannum.setText(mUserInfors.get(position).getDigg_count());
helper.tv_plnum.setText(mUserInfors.get(position).getComment_count());
helper.tv_content.setText(content);
if (mUserInfors.get(position).getType().equals("post")) {
helper.rel_photo.setVisibility(View.GONE);
helper.tv_content.setVisibility(View.VISIBLE);
} else {
if (TextUtils.isEmpty(content)) {
helper.tv_content.setVisibility(View.GONE);
} else {
helper.tv_content.setVisibility(View.VISIBLE);
}
helper.rel_photo.setVisibility(View.VISIBLE);
}
return convertView;
}
Above is the code of getview, I was in the use of staggeredgridview Etsy ,when I scroll the screen,this problem is occurs, a time when the position is out of confusion, as if the location of the position did not be remembered.
The following is a screenshot of position getview:
This issue comes only if you are not controlling getCount() and getItem() methods. Make sure that you are returning your list size as in getCount() like this :
#Override
public int getCount() {
return list.size();
}
and getItem() as :
#Override
public SetterGetterClassName getItem(int position) {
return list.get(position);
}
This is my complete code :
enter code here
public class UserDetailsAdapter2 extends BaseAdapter {
//private HashMap<Integer, View> viewMap;
private DisplayImageOptions mDisplayOption = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true)
.showStubImage(R.drawable.empty_activity_icon).showImageForEmptyUri(R.drawable.empty)
.showImageOnFail(R.drawable.empty_activity_icon).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(400)).considerExifParams(true)
.build();
private Context mContext;
private List<CellQzones> mUserInfors;
private UserInfor mUser;
private String TAG = "UserDetailsAdapter2";
private final Random mRandom;
private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
//private ImageLoader2 mImageLoader2;
public UserDetailsAdapter2(Context context, List<CellQzones> mDatas, UserInfor user) {
mContext = context;
mUserInfors = mDatas;
mUser = user;
mRandom = new Random();
//viewMap=new HashMap<Integer, View>();
}
#Override
public int getCount() {
return mUserInfors.size();
}
#Override
public Object getItem(int position) {
return mUserInfors.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder helper = null;
Log.i("StaggeredGridView--Adapter:", "position:" + position);
// if(!viewMap.containsKey(position) || viewMap.get(position) == null){
if(convertView ==null){
helper = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user_details_adapter, null);
helper.tv_content = (EmojiconTextView) convertView.findViewById(R.id.txt_content);
helper.tv_time = (TextView) convertView.findViewById(R.id.txt_time);
helper.tv_zannum = (TextView) convertView.findViewById(R.id.tv_zan_num);
helper.tv_plnum = (TextView) convertView.findViewById(R.id.tv_pl_num);
helper.iv_show = (DynamicHeightImageView) convertView.findViewById(R.id.img_content);// 展示的图片
helper.img_zan = (ImageView) convertView.findViewById(R.id.img_normal);// 已经赞过的改颜色。
helper.rel_photo = (RelativeLayout) convertView.findViewById(R.id.rel_photo);
convertView.setTag(helper);
} else {
//convertView = viewMap.get(position);
helper = (ViewHolder) convertView.getTag();
}
double positionHeight = getPositionRatio(position);
Log.d(TAG, "getView position:" + position + " h:" + positionHeight);
helper.iv_show.setHeightRatio(positionHeight);
String imgeurl = "";
List<Map<String, String>> listget = mUserInfors.get(position).getmAttach();
if (listget != null && listget.size() > 0) {
for (int i = 0; i < listget.size(); i++) {
Map<String, String> map = listget.get(i);
if (map != null) {
if (map.get("attach_middle") != null) {
imgeurl = map.get("attach_middle");
if (!TextUtils.isEmpty(imgeurl)) {
break;
}
}
}
}
}
List<Map<String, String>> diggerlist = mUserInfors.get(position).getDigger_list();
if (diggerlist.size() > 0) {
helper.tv_zannum.setText(diggerlist.size() + "");
boolean state = getCheckstate(diggerlist);
if (state) {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.zan));
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
} else {
helper.img_zan.setImageDrawable(mContext.getResources().getDrawable(R.drawable.normalzan));
}
if (!TextUtils.isEmpty(imgeurl)) {
//mImageLoader2.loadImage(imgeurl,helper.iv_show, true);
ImageLoader.getInstance().displayImage(imgeurl, helper.iv_show, mDisplayOption);
} else {
helper.iv_show.setImageDrawable(mContext.getResources().getDrawable(R.drawable.empty_activity_icon));
}
String content = mUserInfors.get(position).getContent();
String time = mUserInfors.get(position).getCtime();
helper.tv_time.setText(time.substring(5));
helper.tv_zannum.setText(mUserInfors.get(position).getDigg_count());
helper.tv_plnum.setText(mUserInfors.get(position).getComment_count());
helper.tv_content.setText(content);
if (mUserInfors.get(position).getType().equals("post")) {
helper.rel_photo.setVisibility(View.GONE);
helper.tv_content.setVisibility(View.VISIBLE);
} else {
if (TextUtils.isEmpty(content)) {
helper.tv_content.setVisibility(View.GONE);
} else {
helper.tv_content.setVisibility(View.VISIBLE);
}
helper.rel_photo.setVisibility(View.VISIBLE);
}
return convertView;
}
public class ViewHolder {
EmojiconTextView tv_content;
TextView tv_time;
TextView tv_zannum;
TextView tv_plnum;
DynamicHeightImageView iv_show;
ImageView img_zan;
RelativeLayout rel_photo;
}
private double getPositionRatio(final int position) {
double ratio = sPositionHeightRatios.get(position, 0.0);
// if not yet done generate and stash the columns height
// in our real world scenario this will be determined by
// some match based on the known height and width of the image
// and maybe a helpful way to get the column height!
if (ratio == 0) {
ratio = getRandomHeightRatio();
sPositionHeightRatios.append(position, ratio);
Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
}
return ratio;
}
private double getRandomHeightRatio() {
return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5
// the width
}
/** 得到checkbox的赞的状态 **/
private boolean getCheckstate(List<Map<String, String>> diggerlist) {
for (int i = 0; i < diggerlist.size(); i++) {
Map<String, String> mp = diggerlist.get(i);
String uid = mUser.getUid();
String mUid = mp.get("uid");
// 如果有就设置true。
if (uid.equals(mUid)) {
return true;
}
}
return false;
}
}

OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available

I am having this error while scrolling list view with items.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available
Can anyone help please?
EDIT
public class ItemsListAdapter2 extends BaseAdapter {
private final float NUMBER_OF_ITEMS_PER_GRID = 2;
private final int AD_POSITION = 4;
private Context context;
private ArrayList<ArrayList<ItemResponse>> allData = new ArrayList<ArrayList<ItemResponse>>();
public class ViewHolder {
// for Item1
LinearLayout itemLayout1;
ImageView itemImage1;
TextView itemDate1;
ImageView itemTagImage1;
TextView normalItemPrice1;
TextView pinnedItemPrice1;
TextView itemTitle1;
TextView itemDescription1;
// for Item2
LinearLayout itemLayout2;
ImageView itemImage2;
TextView itemDate2;
ImageView itemTagImage2;
TextView normalItemPrice2;
TextView pinnedItemPrice2;
TextView itemTitle2;
TextView itemDescription2;
RelativeLayout adLayout;
ImageView adUnit;
}
public ItemsListAdapter2(Context context, ArrayList<ItemResponse> data) {
this.context = context;
setData(data);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_listings2, null);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemLayout1 = (LinearLayout) convertView.findViewById(R.id.item1_layout);
holder.itemImage1 = (ImageView) convertView.findViewById(R.id.item_image1);
holder.itemDate1 = (TextView) convertView.findViewById(R.id.item_date1);
holder.itemTagImage1 = (ImageView) convertView.findViewById(R.id.tag_image1);
holder.normalItemPrice1 = (TextView) convertView.findViewById(R.id.normal_item_price1);
holder.pinnedItemPrice1 = (TextView) convertView.findViewById(R.id.pinned_item_price1);
holder.itemTitle1 = (TextView) convertView.findViewById(R.id.item_title1);
holder.itemDescription1 = (TextView) convertView.findViewById(R.id.item_description1);
holder.itemLayout2 = (LinearLayout) convertView.findViewById(R.id.item2_layout);
holder.itemImage2 = (ImageView) convertView.findViewById(R.id.item_image2);
holder.itemDate2 = (TextView) convertView.findViewById(R.id.item_date2);
holder.itemTagImage2 = (ImageView) convertView.findViewById(R.id.tag_image2);
holder.normalItemPrice2 = (TextView) convertView.findViewById(R.id.normal_item_price2);
holder.pinnedItemPrice2 = (TextView) convertView.findViewById(R.id.pinned_item_price2);
holder.itemTitle2 = (TextView) convertView.findViewById(R.id.item_title2);
holder.itemDescription2 = (TextView) convertView.findViewById(R.id.item_description2);
holder.adLayout = (RelativeLayout) convertView.findViewById(R.id.banner_ad);
holder.adUnit = (ImageView) convertView.findViewById(R.id.ad_view_image);
if (allData.get(position) != null && allData.get(position).size() > 0) {
setItem1Data(holder, position);
setItem2Data(holder, position);
}
if ((position + 1) % AD_POSITION == 0) {
// show ad
holder.adLayout .setVisibility(View.VISIBLE);
//initializeBannerAd(convertView, holder.adUnit);
} else {
holder.adLayout .setVisibility(View.GONE);
}
return convertView;
}
#Override
public int getCount() {
return allData.size();
}
#Override
public Object getItem(int position) {
try {
return allData.get(position);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
#Override
public long getItemId(int position) {
try {
return allData.indexOf(getItem(position));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return -1;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
private void initData (ArrayList<ItemResponse> data) {
int numberOfItems = (int) Math.ceil(data.size() / NUMBER_OF_ITEMS_PER_GRID);
ArrayList<ArrayList<ItemResponse>> tempData = new ArrayList<ArrayList<ItemResponse>>(numberOfItems);
for (int i = 0; i < numberOfItems; i++) {
ArrayList<ItemResponse> items = new ArrayList<ItemResponse>();
for (int j = 0; j < NUMBER_OF_ITEMS_PER_GRID; j++) {
try {
items.add(data.get(j));
} catch (Exception e) {
e.printStackTrace();
}
}
tempData.add(i, items);
// clear
data.removeAll(items);
}
for (int n = 0; n < tempData.size(); n++) {
allData.add(tempData.get(n));
}
}
public void setData (ArrayList<ItemResponse> data) {
allData.clear();
ArrayList<ItemResponse> mData = new ArrayList<ItemResponse>();
for (int i = 0; i < data.size(); i++) {
mData.add(data.get(i));
}
initData(mData);
}
public void setItem1Data (ViewHolder holder , int position) {
try {
holder.itemLayout1.setVisibility(View.VISIBLE);
final ItemResponse current = allData.get(position).get(0);
if (current != null) {
if (current.getId() == ForSaleConstants.POST_AD_LISTING_ID) {
String postAdPlaceholder = "";
ForSaleApplication app = (ForSaleApplication) context.getApplicationContext();
if (app.getDefaultLocale().toLowerCase().startsWith(ForSaleConstants.ARABIC_LANGUAGE)) {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_AR_URL_KEY);
} else {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_EN_URL_KEY);
}
if (PhoneUtils.isEmpty(postAdPlaceholder) == false) {
PhoneUtils.setImage(context, holder.itemImage1, postAdPlaceholder);
}
holder.itemDate1.setVisibility(View.GONE);
holder.itemTagImage1.setVisibility(View.GONE);
holder.normalItemPrice1.setVisibility(View.GONE);
holder.pinnedItemPrice1.setVisibility(View.GONE);
holder.itemTitle1.setVisibility(View.GONE);
holder.itemDescription1.setVisibility(View.GONE);
// TODO handle on click listener for placeholder.
} else {
holder.itemDate1.setVisibility(View.VISIBLE);
holder.itemTagImage1.setVisibility(View.VISIBLE);
holder.itemTitle1.setVisibility(View.VISIBLE);
holder.itemDescription1.setVisibility(View.VISIBLE);
if (current.getImages() != null && current.getImages().size() > 0) {
PhoneUtils.setImage(context, holder.itemImage1, current.getImages().get(0));
}
holder.itemDate1.setText(current.getDatePublished());
if (current.isPinned() == true) {
holder.itemTagImage1.setImageResource(R.drawable.tag_pinned);
}
if (current.isPinned() == true) {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.pinnedItemPrice1.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.pinnedItemPrice1.setText("" + current.getAskingPrice());
holder.normalItemPrice1.setVisibility(View.GONE);
holder.pinnedItemPrice1.setVisibility(View.VISIBLE);
holder.itemTagImage1.setVisibility(View.VISIBLE);
} else {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.normalItemPrice1.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.normalItemPrice1.setText("" + current.getAskingPrice());
holder.normalItemPrice1.setVisibility(View.VISIBLE);
holder.pinnedItemPrice1.setVisibility(View.GONE);
holder.itemTagImage1.setVisibility(View.GONE);
}
holder.itemTitle1.setText(current.getTitle());
holder.itemDescription1.setText(current.getDescription());
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ItemDetailsActivity.class);
intent.putExtra(ForSaleConstants.ACTIVITY_ITEM_OBJECT, current);
context.startActivity(intent);
}
};
holder.itemImage1.setOnClickListener(clickListener);
holder.itemTitle1.setOnClickListener(clickListener);
holder.itemDescription1.setOnClickListener(clickListener);
}
}
} catch (Exception e) {
e.printStackTrace();
holder.itemLayout1.setVisibility(View.INVISIBLE);
}
}
public void setItem2Data (ViewHolder holder , int position) {
try {
holder.itemLayout2.setVisibility(View.VISIBLE);
final ItemResponse current = allData.get(position).get(1);
if (current != null) {
if (current.getId() == ForSaleConstants.POST_AD_LISTING_ID) {
String postAdPlaceholder = "";
ForSaleApplication app = (ForSaleApplication) context.getApplicationContext();
if (app.getDefaultLocale().toLowerCase().startsWith(ForSaleConstants.ARABIC_LANGUAGE)) {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_AR_URL_KEY);
} else {
postAdPlaceholder = PhoneUtils.getStringFromSharedPreference(context, ForSaleConstants.PINNING_IMAGE_EN_URL_KEY);
}
if (PhoneUtils.isEmpty(postAdPlaceholder) == false) {
PhoneUtils.setImage(context, holder.itemImage2, postAdPlaceholder);
} else {
PhoneUtils.setImage(context, holder.itemImage2, null, R.drawable.placeholder_squre);
}
holder.itemDate2.setVisibility(View.GONE);
holder.itemTagImage2.setVisibility(View.GONE);
holder.normalItemPrice2.setVisibility(View.GONE);
holder.pinnedItemPrice2.setVisibility(View.GONE);
holder.itemTitle2.setVisibility(View.GONE);
holder.itemDescription2.setVisibility(View.GONE);
// TODO handle on click listener for placeholder.
} else {
holder.itemDate2.setVisibility(View.VISIBLE);
holder.itemTagImage2.setVisibility(View.VISIBLE);
holder.itemTitle2.setVisibility(View.VISIBLE);
holder.itemDescription2.setVisibility(View.VISIBLE);
if (current.getImages() != null && current.getImages().size() > 0) {
PhoneUtils.setImage(context, holder.itemImage2, current.getImages().get(0));
}
holder.itemDate2.setText(current.getDatePublished());
if (current.isPinned() == true) {
holder.itemTagImage2.setImageResource(R.drawable.tag_pinned);
} else {
holder.itemTagImage2.setImageResource(R.drawable.tag);
}
if (current.isPinned() == true) {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.pinnedItemPrice2.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.pinnedItemPrice2.setText("" + current.getAskingPrice());
holder.normalItemPrice2.setVisibility(View.GONE);
holder.pinnedItemPrice2.setVisibility(View.VISIBLE);
holder.itemTagImage2.setVisibility(View.VISIBLE);
} else {
if (ForSaleDataManager.getInstance().getCurrentRegion() != null)
holder.normalItemPrice2.setText(current.getAskingPrice() + " " + ForSaleDataManager.getInstance().getCurrentRegion().getRegionCode());
else
holder.normalItemPrice2.setText("" + current.getAskingPrice());
holder.normalItemPrice2.setVisibility(View.VISIBLE);
holder.pinnedItemPrice2.setVisibility(View.GONE);
holder.itemTagImage2.setVisibility(View.GONE);
}
holder.itemTitle2.setText(current.getTitle());
holder.itemDescription2.setText(current.getDescription());
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ItemDetailsActivity.class);
intent.putExtra(ForSaleConstants.ACTIVITY_ITEM_OBJECT, current);
context.startActivity(intent);
}
};
holder.itemImage2.setOnClickListener(clickListener);
holder.itemTitle2.setOnClickListener(clickListener);
holder.itemDescription2.setOnClickListener(clickListener);
}
}
} catch (Exception e) {
e.printStackTrace();
holder.itemLayout2.setVisibility(View.INVISIBLE);
}
}
}
and also find the loading method, I am implementing on scroll load more items
private void loadData (boolean inBackground) {
int categoryId = -1;
if (mParentCategory != null)
categoryId = mParentCategory.getId();
mIsInBackground = inBackground;
if (mIsInBackground == false)
showProgressDialog();
else
disableBackButton();
// TODO districts.
ForSaleServerManager.getInstance().getListings(this, mSearchQuery,
categoryId, -1, mSellingTypeId, mPageNumber, this);
}
and in the following is setting data in the adapter
if (mPageNumber == 1) {
// add all pinning items.
if (items.getPinnedItems() != null && items.getPinnedItems().size() > 0)
allItems.addAll(items.getPinnedItems());
if (mMode == MODE_SEARCH) {
// handle post ad listing item.
if ((allItems.size() % 2) != 0)
allItems.add(new ItemResponse(ForSaleConstants.POST_AD_LISTING_ID));
}
}
// add all normal items.
if (items.getNormalItems() != null && items.getNormalItems().size() > 0)
for (int i = 0; i < items.getNormalItems().size(); i++) {
if (allItems.contains(items.getNormalItems().get(i)) == false)
allItems.add(items.getNormalItems().get(i));
}
if (allItems != null && allItems.size() > 0) {
if (mAdapter == null) {
mAdapter = new ItemsListAdapter2(ItemsActivity.this, allItems);
mListView.setAdapter(mAdapter);
mListView.setVisibility(View.VISIBLE);
mNoDataFound.setVisibility(View.GONE);
} else {
mAdapter.setData(allItems);
mAdapter.notifyDataSetChanged();
mListView.setVisibility(View.VISIBLE);
mNoDataFound.setVisibility(View.GONE);
}
} else {
mListView.setVisibility(View.GONE);
mNoDataFound.setVisibility(View.VISIBLE);
showNoData(R.drawable.icon_listing_unselected, R.string.error_categories_found);
}

Sectioning date header in a ListView that has adapter extended by CursorAdapter

I am trying to build a demo chatting App.I want to show the messages with section headers as Dates like "Today","Yesterday","May 21 2015" etc.I have managed to achieve this but since the new View method gets called whenever I scroll the list.The headers and messages get mixed up.
For simplicity, I have kept the header in the layouts itself and changing its visibility(gone and visible) if the date changes.
Can you help me out with this? Let me know if anyone needs any more info to be posted in the question.
public class ChatssAdapter extends CursorAdapter {
private Context mContext;
private LayoutInflater mInflater;
private Cursor mCursor;
private String mMyName, mMyColor, mMyImage, mMyPhone;
// private List<Contact> mContactsList;
private FragmentActivity mActivity;
private boolean mIsGroupChat;
public ChatssAdapter(Context context, Cursor c, boolean groupChat) {
super(context, c, false);
mContext = context;
mMyColor = Constants.getMyColor(context);
mMyName = Constants.getMyName(context);
mMyImage = Constants.getMyImageUrl(context);
mMyPhone = Constants.getMyPhone(context);
mIsGroupChat = groupChat;
mCursor = c;
// mActivity = fragmentActivity;
/*try {
mContactsList = PinchDb.getHelper(mContext).getContactDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
boolean type;
if (mIsGroupChat)
type = cursor.getString(cursor.getColumnIndex(Chat.COLMN_CHAT_USER)).compareTo(mMyPhone) == 0;
else type = cursor.getInt(cursor.getColumnIndex(Chat.COLMN_FROM_ME)) > 0;
if (type) {
return 0;
} else {
return 1;
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = null;
int itemViewType = getItemViewType(cursor);
if (v == null) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (itemViewType == 0) {
v = mInflater.inflate(R.layout.row_chat_outgoing, parent, false);
} else {
v = mInflater.inflate(R.layout.row_chat_incoming, parent, false);
}
}
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = new ViewHolder();
View v = view;
final Chat chat = new Chat(cursor);
boolean fromMe = mIsGroupChat ? chat.getUser().compareTo(mMyPhone) == 0 : chat.isFrom_me();
if (fromMe) {
// LOGGED IN USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
int color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(color);
holder.chat_name.setText("#You");
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setText(theRest);
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
//holder.chat_text.setText("");
}
updateTimeTextColorAsPerStatus(holder.chat_time, chat.getStatus());
v.setTag(holder);
} else {
// OTHER USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
holder.chat_image = (ImageView) v
.findViewById(R.id.chat_profile_image);
String image = cursor.getString(cursor.getColumnIndex("image"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String color = cursor.getString(cursor.getColumnIndex("color"));
// set the values...
if (holder.chat_image != null) {
MImageLoader.displayImage(context, image, holder.chat_image, R.drawable.round_user_place_holder);
}
int back_color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(back_color);
holder.chat_name.setText(name);
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
Log.d("eywa", "str date is ::::: " + str_date + " pref date is :::::: " + pref_date);
/*if (!TextUtils.isEmpty(pref_date)) {
if (!pref_date.contains(str_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
} else {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
}*/
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
// holder.chat_text.setText("");
}
String phone = cursor.getString(cursor.getColumnIndex("user"));
final Contact contact = new Contact(name, phone, "", color, image);
if (holder.chat_image != null) {
holder.chat_image.setTag(contact);
// holder.chat_name.setTag(contact);
holder.chat_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact con = (Contact) v.getTag();
Intent intent = new Intent(mContext, OtherProfileActivity.class);
intent.putExtra(Constants.EXTRA_CONTACT, con);
mContext.startActivity(intent);
}
});
}
v.setTag(holder);
}
/*else
{
view=
}*/
}
private void updateTimeTextColorAsPerStatus(TextView chat_time, int status) {
if (status == 0) chat_time.setVisibility(View.INVISIBLE);
else {
chat_time.setVisibility(View.VISIBLE);
/* if (status == 1)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.white));*/
if (status == 2)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.darker_gray));
else if (status == 3)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.black));
}
}
#Override
public int getViewTypeCount() {
return 2;
}
public class ViewHolder {
public StyleableTextView chat_name;
public StyleableTextView chat_time;
public StyleableTextView chat_tag;
public ImageView chat_image;
public TextView chat_header_text;
}
#Override
public int getCount() {
if (getCursor() == null) {
return 0;
} else {
return getCursor().getCount();
}
}
}

Categories

Resources