How to add timestamps to an adapter - android

I am trying to make a Chat bubble and I need to insert the timestamps in each bubble, I have my adapter to insert the messages but I do not know how to add the timestamps, someone could tell me how to do it.
Here the MainActivity code:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private View btnSend;
private EditText editText;
boolean myMessage = true;
private List<ChatBubble> ChatBubbles;
private ArrayAdapter<ChatBubble> adapter;
private TextView dateTimeTx;
private TextView dateTimeRx;
private String dateTime;
private String timestamp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatBubbles = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_msg);
btnSend = findViewById(R.id.btn_chat_send);
editText = (EditText) findViewById(R.id.msg_type);
//set ListView adapter first
adapter = new MessageAdapter(this, R.layout.tx_chat_bubble, ChatBubbles);
listView.setAdapter(adapter);
//event for button SEND
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please input some text...", Toast.LENGTH_SHORT).show();
} else {
//add message to list
ChatBubble ChatBubble = new ChatBubble(editText.getText().toString(), myMessage, timestamp.toString() );
ChatBubbles.add(ChatBubble);
adapter.notifyDataSetChanged();
editText.setText("");
if (myMessage) {
myMessage = false;
} else {
myMessage = true;
}
}
}
});
}
}
But I have a error in :
ChatBubble ChatBubble = new ChatBubble(editText.getText().toString(), myMessage, timestamp.toString() );
Here mi Adapter code:
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
private String dateTime;
private SimpleDateFormat simpleDateFormat ;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
String isoDatePattern = "dd/MM/yyyy HH:mm";
simpleDateFormat = new SimpleDateFormat(isoDatePattern);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.tx_chat_bubble;
} else {
layoutResource = R.layout.rx_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
holder.dateTimeTx.setText(ChatBubble.getTimestamp());
return convertView;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return position % 2;
}
private class ViewHolder {
private TextView msg;
private TextView dateTimeTx;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
dateTimeTx = (TextView) v.findViewById(R.id.time_msg);
}
}
private String readFechaActual(long timestamp){
return simpleDateFormat.format(new Date(timestamp));
}
}
But I have another error in:
holder.dateTimeTx.setText(ChatBubble.getTimestamp());
Here is the ChatBubble class:
public class ChatBubble {
private String content;
private boolean myMessage;
private long timestamp;
public ChatBubble(String content, boolean myMessage, long timestamp) {
this.content = content;
this.myMessage = myMessage;
this.timestamp = timestamp;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
public long getTimestamp() {
return timestamp;
}
}

Create single (to avoid unused resource requirements) SimpleDateFormat in an adapter constructor:
private SimpleDateFormat simpleDateFormat ;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
String isoDatePattern = "dd/MM/yyyy HH:mm";
simpleDateFormat = new SimpleDateFormat(isoDatePattern);
}
Update the helper method to return formatted date string:
private String readFechaActual(long timestamp){
return simpleDateFormat.format(new Date(timestamp));
}
}
Use it in getView:
//set message content
holder.msg.setText(ChatBubble.getContent());
holder.dateTimeTx.setText("" + ChatBubble.getTimestamp()); // <--- ADD HERE
The adapter only connects View and Model, but actual data keeps in model, so you should change the BubbleChat class and add timestamp field:
public class ChatBubble {
private String content;
private boolean myMessage;
private long timestamp;
public ChatBubble(String content, boolean myMessage, long timestamp) {
this.content = content;
this.myMessage = myMessage;
this.timestamp = timestamp;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
public long getTimestamp() {
return timestamp;
}
}

You should set the time in getView, same way you set the bubble's message.
You already have the field in the ViewHolder.
Also, ChatBubble ChatBubble = getItem(position); should be ChatBubble chatBubble = getItem(position);
And please use RecyclerView

Create a model
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Context mContext, Date curdate, Date olddate) {
String y = " "+mContext.getString(R.string.year);
String ys = " "+mContext.getString(R.string.years);
String m = " "+mContext.getString(R.string.month);
String ms = " "+mContext.getString(R.string.months);
String d = " "+mContext.getString(R.string.day);
String ds = " "+mContext.getString(R.string.days);
String h = " "+mContext.getString(R.string.hour);
String hs = " "+mContext.getString(R.string.hours);
String mm = " "+mContext.getString(R.string.minute);
String mms= " "+mContext.getString(R.string.minutes);
String s = " "+mContext.getString(R.string.second);
String ss = " "+mContext.getString(R.string.seconds);
String a = " "+mContext.getString(R.string.ago);
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? y : ys) + a);
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? m : ms) + a);
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? d : ds) + a);
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? h : hs) + a);
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? mm : mms) + a);
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? s : ss) + a);
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
Create Utils.java and add this
public static Date getDefaultDate(){
SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
f.setTimeZone(TimeZone.getDefault());
Date nowDate = new Date();
try {
nowDate = dateFormatter.parse(f.format(new Date()));
}catch (ParseException e){
e.printStackTrace();
}
return nowDate;
}
public static Date newDate(String timeStamp){
Date OurDate = null;
try{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(timeStamp);
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormatter.setTimeZone(TimeZone.getDefault());
String n = dateFormatter.format(value);
OurDate = dateFormatter.parse(n);
}catch (ParseException e){
e.printStackTrace();
}
return OurDate;
}
For pass date into Adapter
TimeDifference now = new TimeDifference(mContext,Utils.getDefaultDate(),Utils.newDate("Your current time");
Toast.makeText(context, "Posted by "+now.getDifferenceString(), Toast.LENGTH_SHORT).show();

Related

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

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;
}
}

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

Can fragments retain the state of collected data of cardviews

Before I change my design of my android application, I was wondering if I can retain the state of my fragment including all data collected when it is recreated. In my fragment i have an async task that collects the proper data usinf json and it publishes them to diffeerent cardviews. Here is my code:
LatestEventsFragment.java
public class LatestEventsFragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<Event> arrayList = new ArrayList();
ProgressDialog progressDialog;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setRetainInstance(true);
View view = inflater.inflate(R.layout.events_list, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView = (RecyclerView)view.findViewById(R.id.events_recycler);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
adapter = new EventsRecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
EventsAsyncTask eventsAsyncTask = new EventsAsyncTask();
eventsAsyncTask.execute();
return view;
}
class EventsAsyncTask extends AsyncTask<String, Event, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Please wait...");
progressDialog.setMessage("Loading");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Event... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected String doInBackground(String... params) {
try {
ServerConfig serverConfig = new ServerConfig();
URL url = new URL(serverConfig.getEvents_url());
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while((line = bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
String jsonString = JO.get("image").toString();
byte[] temp = Base64.decode(jsonString.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(temp, 0, temp.length);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UCT"));
Date date = dateFormat.parse(JO.getString("date_posted"));
Date server_date = dateFormat.parse(JO.getString("server_date"));
Event event = new Event(JO.getString("name"), decodedByte, JO.getInt("views"), date, server_date);
publishProgress(event);
Thread.sleep(500);
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
}
EventsRecyclerAdapter.java
public class EventsRecyclerAdapter extends RecyclerView.Adapter<EventsRecyclerAdapter.RecyclerViewHolder>{
ArrayList<Event> arrayList = new ArrayList<>();
public EventsRecyclerAdapter(ArrayList<Event> arrayList){
this.arrayList = arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.latest_events_card, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
Event event = arrayList.get(position);
try{
String views = String.valueOf(event.getViews())+" views";
String date_string = getTime(event.getServer_date().getTime() - event.getDate_posted().getTime());
holder.name.setText(event.getName());
holder.image.setImageBitmap(event.getImage());
holder.views.setText(views);
holder.date_posted.setText(date_string);
}catch (Exception e){
e.printStackTrace();
}
}
private String getTime(Long time_difference){
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = time_difference / daysInMilli;
int daysInt = (int)elapsedDays;
time_difference = time_difference % daysInMilli;
long elapsedHours = time_difference / hoursInMilli;
int hoursInt = (int)elapsedHours;
time_difference = time_difference % hoursInMilli;
long elapsedMinutes = time_difference / minutesInMilli;
int minutesInt = (int)elapsedMinutes;
//time_difference = time_difference % minutesInMilli;
//long elapsedSeconds = time_difference / secondsInMilli;
String date_string = String.valueOf(daysInt);
if(daysInt > 0) {
if (daysInt == 1) {
date_string = "1 Day";
} else if (daysInt > 1) {
date_string = daysInt + " Days";
}
}else if(hoursInt > 0){
if(hoursInt == 1){
date_string = "1 Hour ";
if(minutesInt > 1){
date_string = date_string + minutesInt + " Minutes";
}
} else if(hoursInt > 1){
date_string = hoursInt + " Hours ";
if(minutesInt > 1){
date_string = date_string + minutesInt + " Minutes";
}
}
}else if(minutesInt > 0){
if (minutesInt == 1) {
date_string = "1 Minute";
} else if (minutesInt > 1) {
date_string = minutesInt + " Minutes";
}
}
return date_string + " ago";
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
protected TextView name, views, date_posted, start_date, end_date;
protected ImageView image;
public RecyclerViewHolder(View v){
super(v);
name = (TextView)v.findViewById(R.id.name);
image = (ImageView)v.findViewById(R.id.thumbnail);
views = (TextView)v.findViewById(R.id.views);
date_posted = (TextView)v.findViewById(R.id.date_posted);
}
}
}
and finally Events.java
public class Event {
private int id;
private String name;
private String description;
private String start_date;
private String end_date;
private double entrance_fee;
private Bitmap image;
private int views;
private Date date_posted;
private Date server_date;
public Event(String name, Bitmap image, int views, Date date_posted, Date server_date){
//int id, String name, , String start_date, double entrance_fee, Bitmap image, int views
this.setDescription(description);
this.setEnd_date(end_date);
this.setEntrance_fee(entrance_fee);
this.setId(id);
this.setImage(image);
this.setName(name);
this.setViews(views);
this.setStart_date(start_date);
this.setDate_posted(date_posted);
this.setServer_date(server_date);
}
public Date getServer_date() {
return server_date;
}
public void setServer_date(Date server_date) {
this.server_date = server_date;
}
public Date getDate_posted() {
return date_posted;
}
public void setDate_posted(Date date_posted) {
this.date_posted = date_posted;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public double getEntrance_fee() {
return entrance_fee;
}
public void setEntrance_fee(double entrance_fee) {
this.entrance_fee = entrance_fee;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
You can use onSaveInstanceState inside your Fragment to save your data, then check the savedInstanceState variable inside onCreateView to see if it has data. If it does, just retrieve the data to recreate your view.
Inside Fragment:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
if(mDataToSave != null) {
savedInstanceState.putString("myData", mDataToSave);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
if(savedInstanceState != null){
String restoredData = (String)savedInstanceState.getString("myData");
//do something with restoredData
}
return rootView;
}
Just remember to change the put and get: savedInstanceState.putString() to savedInstanceState.put<WhateverYourDataTypeIs>()
If you're adding your Fragment through a Fragment Transaction in your Main Activity, make sure to only add it if the Main Activity's savedInstanceState is null. That way you won't replace the Fragment if it's already been added.
Inside Activity (if you have a Fragment Transaction):
if(savedInstanceState == null) {
Fragment newFragment = new MyFragment();
//add main fragment to fragment frame
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.fragment_container, newFragment).commit();
}

listview not updated baseadapter

i working baseadapter.
i have two datetimeformat 09/01/2014 and 09/10/2014.i checked days between there datetimes
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
for (int i = 0; i < delta; i++) {
}
return String.valueOf(delta) ;
}
else {
delta *= -1;
return String.valueOf(delta);
}
}
and also i wrote funtciton to change there datetimes format 09/01/2014 i changed it 1 Sep
public static String dateFormatterforLukka(String inputDate,int lenght) {
String inputFormat = "MM/dd/yyyy";
String outputFormat = String.valueOf(lenght)+"MMM";
Date parsed = null;
String outputDate = "";
try {
SimpleDateFormat df_input = new SimpleDateFormat(inputFormat,
new Locale("en", "US"));
SimpleDateFormat df_output = new SimpleDateFormat(outputFormat,
new Locale("en", "US"));
parsed = df_input.parse(inputDate);
outputDate = df_output.format(parsed);
Log.wtf("outputDate", outputDate);
} catch (Exception e) {
outputDate = inputDate;
}
return outputDate;
}
now i want to add my datetimes in listview like this .betweeen days there two datetimes . 1 Sep,2 Sep etc...
BaseAdapter Code
public class HollAdapters extends BaseAdapter {
private Context mContext;
private final ArrayList<CinemaInfoModel> hollitems;
private CinemaInfoModel objBean;
private TextView start_time,holle,time;
private static LayoutInflater inflater = null;
public HollAdapters(Context context, ArrayList<CinemaInfoModel> hollitems) {
mContext = context;
this.hollitems = hollitems;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return hollitems.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
grid = new View(mContext);
grid = inflater.inflate(R.layout.cinema_holl_adapter, null);
start_time = (TextView) grid.findViewById(R.id.adapter_day);
holle = (TextView) grid.findViewById(R.id.adapter_holl);
time = (TextView) grid.findViewById(R.id.adapter_time);
objBean = hollitems.get(position);
start_time.setText(objBean.getStartTime());
holle.setText(objBean.getHole());
String start_time=objBean.getTime();
start_time=start_time.replace(",", "\n");
time.setText(start_time);
return grid;
}
}
this is a main java code
SimpleDateFormat df = new SimpleDateFormat(
"MM/dd/yyyy");
Date _d = df.parse("09/01/2014");
Date _d1 = df.parse("09/10/2014");
SimpleDateFormat new_df = new SimpleDateFormat(
"d MMM");
String _s1 = new_df.format(_d1);
String datetimeis=getDateDiffString(_d1, _d);
Log.wtf("differentis ", datetimeis);
int abc=Integer.parseInt(datetimeis);
for (int l = 0; l < abc; l++) {
String ab = dateFormatterforLukka(timeJsonArray
.getJSONObject(k).getString("start_time"),l++);
Log.wtf("timeeeeeeeee", ab);
cinemaTime.setStartTime(ab);
cinemaTime.setEndTime(_s1);
cinemaTimesArray.add(cinemaTime);
}
when i run my app only 8 sep added always in my listview ,but i loged and in log i have
different result, meybe listview did not updated
what am i doing wrong? if anyone knows solution please help me
Create a methord in adapter class
public void setdata(ArrayList<CinemaInfoModel> hollitems_temp) {
this.hollitems=hollitems_temp;
}
for (int l = 0; l < abc; l++) {
String ab = dateFormatterforLukka(timeJsonArray
.getJSONObject(k).getString("start_time"),l++);
Log.wtf("timeeeeeeeee", ab);
cinemaTime.setStartTime(ab);
cinemaTime.setEndTime(_s1);
cinemaTimesArray.add(cinemaTime);
}
after this loop i am assuming that cinematimesarray is of type CinemaInfoModel
youradapter.setdata(cinemaTimesArray);
youradapter.notifyDataSetChanged();
put debugger in your getview methord and check;

Missing data in Section list view in Android?

I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}

Categories

Resources