Adapter-Showing view only when there is a change in a value - android

Below is my complete adapter class of sendbird chatting.Currently date with time is displayed with every message.viewHolder.getView("left_time") and viewHolder.getView("right_time") are views for displaying date with time and it is calculated in method getDisplayDateTime.I want date with time to be displayed only when there is a change in date.For example if there is set of messages dated 23rd june then date with time should be displayed only for the first message with date 23rd june.
I tried doing that by detecting whenever there is a change in date by storing date in xyz variable and comparing it with date of every message and whenever they are unequal then making date view of that message visible and assigning the new date to xyz variable for comparison with future messages.But this approach fails when i scroll down and scroll up list.
What is the ideal approach for achieving this?
public class SendBirdMessagingAdapter extends BaseAdapter {
private static final int TYPE_UNSUPPORTED = 0;
private static final int TYPE_MESSAGE = 1;
private static final int TYPE_SYSTEM_MESSAGE = 2;
private static final int TYPE_FILELINK = 3;
private static final int TYPE_BROADCAST_MESSAGE = 4;
private static final int TYPE_TYPING_INDICATOR = 5;
private final Context mContext;
private final LayoutInflater mInflater;
private final ArrayList<Object> mItemList;
private Hashtable<String, Long> mReadStatus;
private Hashtable<String, Long> mTypeStatus;
private List<MessagingChannel.Member> mMembers;
private long mMaxMessageTimestamp = Long.MIN_VALUE;
private long mMinMessageTimestamp = Long.MAX_VALUE;
public SendBirdMessagingAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mItemList = new ArrayList<Object>();
mReadStatus = new Hashtable<String, Long>();
mTypeStatus = new Hashtable<String, Long>();
}
#Override
public int getCount() {
return mItemList.size() + ((mTypeStatus.size() <= 0) ? 0 : 1);
}
#Override
public Object getItem(int position) {
if (position >= mItemList.size()) {
ArrayList<String> names = new ArrayList<String>();
for (MessagingChannel.Member member : mMembers) {
if (mTypeStatus.containsKey(member.getId())) {
names.add(member.getName());
}
}
return names;
}
return mItemList.get(position);
}
public void delete(Object object) {
mItemList.remove(object);
}
public void clear() {
mMaxMessageTimestamp = Long.MIN_VALUE;
mMinMessageTimestamp = Long.MAX_VALUE;
mReadStatus.clear();
mTypeStatus.clear();
mItemList.clear();
}
public void resetReadStatus(Hashtable<String, Long> readStatus) {
mReadStatus = readStatus;
}
public void setReadStatus(String userId, long timestamp) {
if (mReadStatus.get(userId) == null || mReadStatus.get(userId) < timestamp) {
mReadStatus.put(userId, timestamp);
}
}
public void setTypeStatus(String userId, long timestamp) {
if (userId.equals(SendBird.getUserId())) {
return;
}
if (timestamp <= 0) {
mTypeStatus.remove(userId);
} else {
mTypeStatus.put(userId, timestamp);
}
}
#Override
public long getItemId(int position) {
return position;
}
public void addMessageModel(MessageModel messageModel) {
if (messageModel.isPast()) {
mItemList.add(0, messageModel);
} else {
mItemList.add(messageModel);
}
updateMessageTimestamp(messageModel);
}
private void updateMessageTimestamp(MessageModel model) {
mMaxMessageTimestamp = mMaxMessageTimestamp < model.getTimestamp() ? model.getTimestamp() : mMaxMessageTimestamp;
mMinMessageTimestamp = mMinMessageTimestamp > model.getTimestamp() ? model.getTimestamp() : mMinMessageTimestamp;
}
public long getMaxMessageTimestamp() {
return mMaxMessageTimestamp == Long.MIN_VALUE ? Long.MAX_VALUE : mMaxMessageTimestamp;
}
public long getMinMessageTimestamp() {
return mMinMessageTimestamp == Long.MAX_VALUE ? Long.MIN_VALUE : mMinMessageTimestamp;
}
public void setMembers(List<MessagingChannel.Member> members) {
mMembers = members;
}
#Override
public int getItemViewType(int position) {
if (position >= mItemList.size()) {
return TYPE_TYPING_INDICATOR;
}
Object item = mItemList.get(position);
if (item instanceof Message) {
return TYPE_MESSAGE;
} else if (item instanceof FileLink) {
return TYPE_FILELINK;
} else if (item instanceof SystemMessage) {
return TYPE_SYSTEM_MESSAGE;
} else if (item instanceof BroadcastMessage) {
return TYPE_BROADCAST_MESSAGE;
}
return TYPE_UNSUPPORTED;
}
#Override
public int getViewTypeCount() {
return 6;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
final Object item = getItem(position);
if (convertView == null || ((ViewHolder) convertView.getTag()).getViewType() != getItemViewType(position)) {
viewHolder = new ViewHolder();
viewHolder.setViewType(getItemViewType(position));
switch (getItemViewType(position)) {
case TYPE_UNSUPPORTED:
convertView = new View(mInflater.getContext());
convertView.setTag(viewHolder);
break;
case TYPE_MESSAGE: {
TextView tv;
CircularImageView iv;
View v;
convertView = mInflater.inflate(R.layout.sendbird_view_messaging_message, parent, false);
v = convertView.findViewById(R.id.left_container);
viewHolder.setView("left_container", v);
iv = (CircularImageView) convertView.findViewById(R.id.img_left_thumbnail);
viewHolder.setView("left_thumbnail", iv);
tv = (TextView) convertView.findViewById(R.id.txt_left);
viewHolder.setView("left_message", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_name);
viewHolder.setView("left_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_time);
viewHolder.setView("left_time", tv);
v = convertView.findViewById(R.id.right_container);
viewHolder.setView("right_container", v);
iv = (CircularImageView) convertView.findViewById(R.id.img_right_thumbnail);
viewHolder.setView("right_thumbnail", iv);
tv = (TextView) convertView.findViewById(R.id.txt_right);
viewHolder.setView("right_message", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_name);
viewHolder.setView("right_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_time);
viewHolder.setView("right_time", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_status);
viewHolder.setView("right_status", tv);
convertView.setTag(viewHolder);
break;
}
case TYPE_SYSTEM_MESSAGE: {
convertView = mInflater.inflate(R.layout.sendbird_view_system_message, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
case TYPE_BROADCAST_MESSAGE: {
convertView = mInflater.inflate(R.layout.sendbird_view_system_message, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
case TYPE_FILELINK: {
TextView tv;
CircularImageView civ;
ImageView iv;
View v;
convertView = mInflater.inflate(R.layout.sendbird_view_messaging_filelink, parent, false);
v = convertView.findViewById(R.id.left_container);
viewHolder.setView("left_container", v);
civ = (CircularImageView) convertView.findViewById(R.id.img_left_thumbnail);
viewHolder.setView("left_thumbnail", civ);
iv = (ImageView) convertView.findViewById(R.id.img_left);
viewHolder.setView("left_image", iv);
tv = (TextView) convertView.findViewById(R.id.txt_left_name);
viewHolder.setView("left_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_time);
viewHolder.setView("left_time", tv);
v = convertView.findViewById(R.id.right_container);
viewHolder.setView("right_container", v);
civ = (CircularImageView) convertView.findViewById(R.id.img_right_thumbnail);
viewHolder.setView("right_thumbnail", civ);
iv = (ImageView) convertView.findViewById(R.id.img_right);
viewHolder.setView("right_image", iv);
tv = (TextView) convertView.findViewById(R.id.txt_right_name);
viewHolder.setView("right_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_time);
viewHolder.setView("right_time", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_status);
viewHolder.setView("right_status", tv);
convertView.setTag(viewHolder);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(mContext)
.setTitle("Foodvite")
.setMessage("Do you want to download this file?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
downloadUrl((FileLink) item, mContext);
} catch (IOException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
}
});
break;
}
case TYPE_TYPING_INDICATOR: {
convertView = mInflater.inflate(R.layout.sendbird_view_typing_indicator, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
}
}
viewHolder = (ViewHolder) convertView.getTag();
switch (getItemViewType(position)) {
case TYPE_UNSUPPORTED:
break;
case TYPE_MESSAGE:
Message message = (Message) item;
if (message.getSenderId().equals(SendBird.getUserId())) {
viewHolder.getView("left_container", View.class).setVisibility(View.GONE);
viewHolder.getView("right_container", View.class).setVisibility(View.VISIBLE);
displayUrlImage(viewHolder.getView("right_thumbnail", CircularImageView.class), message.getSenderImageUrl(), true);
viewHolder.getView("right_name", TextView.class).setText(message.getSenderName());
viewHolder.getView("right_message", TextView.class).setText(message.getMessage());
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp()));
int readCount = 0;
for (String key : mReadStatus.keySet()) {
if (key.equals(message.getSenderId())) {
readCount += 1;
continue;
}
if (mReadStatus.get(key) >= message.getTimestamp()) {
readCount += 1;
}
}
if (readCount < mReadStatus.size()) {
if (mReadStatus.size() - readCount > 1) {
viewHolder.getView("right_status", TextView.class).setText("Unread " + (mReadStatus.size() - readCount));
} else {
viewHolder.getView("right_status", TextView.class).setText("Unread");
}
} else {
viewHolder.getView("right_status", TextView.class).setText("");
}
viewHolder.getView("right_container").setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(mContext)
.setTitle("Foodvite")
.setMessage("Do you want to delete a message?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SendBird.deleteMessage(((Message) item).getMessageId(), new DeleteMessageHandler() {
#Override
public void onError(SendBirdException e) {
e.printStackTrace();
}
#Override
public void onSuccess(long messageId) {
mSendBirdMessagingAdapter.delete(item);
mSendBirdMessagingAdapter.notifyDataSetChanged();
Toast.makeText(mContext, "Message has been deleted.", Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
return true;
}
});
} else {
viewHolder.getView("left_container", View.class).setVisibility(View.VISIBLE);
viewHolder.getView("right_container", View.class).setVisibility(View.GONE);
displayUrlImage(viewHolder.getView("left_thumbnail", CircularImageView.class), message.getSenderImageUrl(), true);
viewHolder.getView("left_name", TextView.class).setText(message.getSenderName());
viewHolder.getView("left_message", TextView.class).setText(message.getMessage());
viewHolder.getView("left_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp()));
if(isGroupChat)
viewHolder.getView("left_name", TextView.class).setVisibility(View.VISIBLE);
else
viewHolder.getView("left_name", TextView.class).setVisibility(View.GONE);
}
break;
case TYPE_SYSTEM_MESSAGE:
SystemMessage systemMessage = (SystemMessage) item;
viewHolder.getView("message", TextView.class).setText(Html.fromHtml(systemMessage.getMessage()));
break;
case TYPE_BROADCAST_MESSAGE:
BroadcastMessage broadcastMessage = (BroadcastMessage) item;
viewHolder.getView("message", TextView.class).setText(Html.fromHtml(broadcastMessage.getMessage()));
break;
case TYPE_FILELINK:
FileLink fileLink = (FileLink) item;
if (fileLink.getSenderId().equals(SendBird.getUserId())) {
viewHolder.getView("left_container", View.class).setVisibility(View.GONE);
viewHolder.getView("right_container", View.class).setVisibility(View.VISIBLE);
displayUrlImage(viewHolder.getView("right_thumbnail", ImageView.class), fileLink.getSenderImageUrl(), true);
viewHolder.getView("right_name", TextView.class).setText(fileLink.getSenderName());
if (fileLink.getFileInfo().getType().toLowerCase().startsWith("image")) {
displayUrlImage(viewHolder.getView("right_image", ImageView.class), fileLink.getFileInfo().getUrl());
} else {
viewHolder.getView("right_image", CircularImageView.class).setImageResource(R.drawable.sendbird_icon_file);
}
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, fileLink.getTimestamp()));
int readCount = 0;
for (String key : mReadStatus.keySet()) {
if (key.equals(fileLink.getSenderId())) {
continue;
}
if (mReadStatus.get(key) < fileLink.getTimestamp()) {
readCount += 1;
}
}
if (readCount < mReadStatus.size() - 1) {
viewHolder.getView("right_status", TextView.class).setText("Unread");
} else {
viewHolder.getView("right_status", TextView.class).setText("");
}
} else {
viewHolder.getView("left_container", View.class).setVisibility(View.VISIBLE);
viewHolder.getView("right_container", View.class).setVisibility(View.GONE);
displayUrlImage(viewHolder.getView("left_thumbnail", ImageView.class), fileLink.getSenderImageUrl(), true);
viewHolder.getView("left_name", TextView.class).setText(fileLink.getSenderName());
if (fileLink.getFileInfo().getType().toLowerCase().startsWith("image")) {
displayUrlImage(viewHolder.getView("left_image", ImageView.class), fileLink.getFileInfo().getUrl());
} else {
viewHolder.getView("left_image", CircularImageView.class).setImageResource(R.drawable.sendbird_icon_file);
}
if(isGroupChat)
viewHolder.getView("left_name", TextView.class).setVisibility(View.VISIBLE);
else
viewHolder.getView("left_name", TextView.class).setVisibility(View.GONE);
viewHolder.getView("left_time", TextView.class).setText(getDisplayDateTime(mContext, fileLink.getTimestamp()));
}
break;
case TYPE_TYPING_INDICATOR: {
int itemCount = ((List) item).size();
String typeMsg = ((List) item).get(0)
+ ((itemCount > 1) ? " +" + (itemCount - 1) : "")
+ ((itemCount > 1) ? " are " : " is ")
+ "typing...";
viewHolder.getView("message", TextView.class).setText(typeMsg);
break;
}
}
return convertView;
}
public boolean checkTypeStatus() {
/**
* Clear an old type status.
*/
for (String key : mTypeStatus.keySet()) {
Long ts = mTypeStatus.get(key);
if (System.currentTimeMillis() - ts > 10 * 1000L) {
mTypeStatus.remove(key);
return true;
}
}
return false;
}
private class ViewHolder {
private Hashtable<String, View> holder = new Hashtable<String, View>();
private int type;
public int getViewType() {
return this.type;
}
public void setViewType(int type) {
this.type = type;
}
public void setView(String k, View v) {
holder.put(k, v);
}
public View getView(String k) {
return holder.get(k);
}
public <T> T getView(String k, Class<T> type) {
return type.cast(getView(k));
}
}
}
private static String getDisplayDateTime(Context context, long milli) {
Date date = new Date(milli);
if (System.currentTimeMillis() - milli < 60 * 60 * 24 * 1000l) {
return DateFormat.getTimeFormat(context).format(date);
}
return DateFormat.getDateFormat(context).format(date) + " " + DateFormat.getTimeFormat(context).format(date);
}

Try below code for your method,
private static String getDisplayDateTime(Context context, long milli, long milli2)
{
Date date = new Date(milli);
Date previousDate = new Date(milli2);
String strCurrentDate = "", strPreviousDate = "";
if (System.currentTimeMillis() - milli < 60 * 60 * 24 * 1000l)
{
strCurrentDate = DateFormat.getTimeFormat(context).format(date);
if(milli2 != -1)
strPreviousDate = DateFormat.getTimeFormat(context).format(previousDate);
//return strCurrentDate.equals(strPreviousDate) ? "" : strCurrentDate;
}
else
{
strCurrentDate = DateFormat.getDateFormat(context).format(date) + " " + DateFormat.getTimeFormat(context).format(date);
if(milli2 != -1)
strPreviousDate = DateFormat.getDateFormat(context).format(strPreviousDate) + " " + DateFormat.getTimeFormat(context).format(strPreviousDate);
}
return strCurrentDate.equals(strPreviousDate) ? "" : strCurrentDate;
}
Now call your methods like below
if(position > 0)
{
final Object previousItem = getItem(position - 1);
Message previousMessage = (Message) previousItem;
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp(), previousMessage.getTimestamp()));
}
else
{
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp(), -1));
}

I had a similar problem (ref this SO Question) few months ago and nothing worked except extending from ArrayAdapter<MyObject> instead of BaseAdapter.
So, change the base class of your adapter to ArrayAdapter<MyObject> and implement the prompted method of the abstract class. you might need to move some you your existing code to these overridden methods for better performance.

You can force the system to redraw all items by calling BaseAdapter.notifyDataSetChanged()

Related

Custom Adapter not Changing Layout According to Condition

I am working on a chat app and I am very new to using ListViews and ArrayAdapters, as well as Custom Adapters. I am having a problem that causes all my items in my list to be of one layout, even they are supposed to change according to a booleans(true would be an outgoing chat bubble, and false would be an incoming chat bubble).
Here is my code for the retreival of the chat(It isn't the whole file, just a snippet):
Variable declarations:
final ArrayList<chatBubble> objects = new ArrayList<>();
final CustomAdapter customAdapter = new CustomAdapter(this, objects);
listView.setAdapter(customAdapter);
Code to get messages and add to list:
mDatabase.child("chat").child("publicDump").child("dumpedMessages").child("message" + i).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String message = dataSnapshot.getValue(String.class);
if (message != null) {
final String extract = message.substring(message.lastIndexOf("<") + 1, message.indexOf(">"));
mDatabase.child("users").child("c").child("emailToUsername").child(mAuth.getCurrentUser().getEmail().replace(".", ",")).child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue(String.class);
if (username != null) {
if (username.equals(extract)) {
Log.i("Extract", extract);
int semicnt = 0;
int num = 0;
//Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, true);
objects.add(chat);
}
}
}
} else {
int semicnt = 0;
int num = 0;
// Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, false);
objects.add(chat);
}
}
}
}
customAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is my code for my chatBubble:
package com.tejasmehta.codeychat;
public class chatBubble {
private String msg;
private String date;
private boolean myMessage;
public chatBubble(String msg, String date, boolean myMessage) {
this.msg = msg;
this.date = date;
this.myMessage = myMessage;
}
public String Msg() {
return msg;
}
public String Date() {
return date;
}
public boolean myMessage() {
return myMessage;
}
}
And here is my code for my customAdapter(which shows that if the boolean, myMessage, is true, it will load a different layout, and a different one for false):
public class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<chatBubble> objects;
private class ViewHolder {
TextView msg;
TextView date;
}
public CustomAdapter(Context context, ArrayList<chatBubble> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public chatBubble getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}
}
Thank You for all of your help!
the problem is your getview
The view is being recycled so convertview already has a layout. so its not being reinflated to the correct layout.
you need to use getViewType() and getViewTypeCount() to tell the listview you want to use different layouts
http://android.amberfog.com/?p=296
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).myMessage()?0:1;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}

How to disable previous items in a ListView

I am trying to develop an activity where there is a custom listView made out of CustomAdapter.
The list consists of a TextView and an EditText. The EditText when clicked, it auto fetches the system time.
What I want is when a particular EditText is filled, I want all the previous(above) list items in the sequence to be disabled.
So far, I have tried using isEnabled() and areAllItemsEnabled() functions returning respective boolean values using position, but however didn’t work.
Please help me achieve the above.
Thanks.
This is my CustomAdapter Class
public class SelectStnListByRoute extends BaseAdapter implements View.OnClickListener {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if(position==position){
return false;
}
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position)); //Here I am getting the position of the row item clicked, where should I put the Onclick false for disabling all of the above fields using the position?
}
});
viewHolder.txtStnDep.setOnClickListener(this);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
int ref;
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case txtArrivalTime:
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
textViewArrVal.setClickable(false);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
break;
case txtDepTime:
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
break;
default:
break;
}
}
public String getCurrentTime(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
You can do this as below mentioned -:
You need to store the position of clicked button was. So initialize a variable in your class
int mButtonSelected = -1;
EDIT 1.
Then make a change to your isEnabled method
#Override
public boolean isEnabled(int position) {
if(position<mButtonSelected){
return false;
}
return true;
}
That will work it if any other button was clicked. but you have to do that in your onClick
mButtonSelected = position;
notifyDataSetChanged();
Let me it worked or not
EDIT
see below changes in your code-:
public class SelectStnListByRoute extends BaseAdapter {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
private SQLiteDB sqLiteDB;
int mArrivalSelected = -1;
int mDepartSelected = -1;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
sqLiteDB = new SQLiteDB(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if (position <= mArrivalSelected) {
return false;
}
return true;
}
public boolean isEnabledd(int position) {
if (position <= mDepartSelected) {
return false;
}
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
if (!isEnabled(position)) {
if (position <= mArrivalSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
if (position < mArrivalSelected) {
viewHolder.txtStnDep.setEnabled(false);
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
}
}
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mArrivalSelected = position;
arrivalClick(view);
notifyDataSetChanged();
}
});
if (!isEnabledd(position)) {
if (position <= mDepartSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
viewHolder.txtStnDep.setEnabled(false);
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
}
viewHolder.txtStnDep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mDepartSelected = position;
departureClick(view);
notifyDataSetChanged();
}
});
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
StnNames pos;
int ref;
}
public void arrivalClick(View view) {
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
int stnId = listItemsArrr.getStnId();
String arrClick = "arrival";
String upSideKm = listItemsArrr.getStnUpsideKm();
String downsideKm = listItemsArrr.getStnDownSideKm();
String arrTime = getCurrentTime();
/* sqLiteDB.open();
*//* long abc = sqLiteDB.insertJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick);*//*
*//* long abcd = sqLiteDB.updateJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick,downsideKm,upSideKm);
Log.e("arrclick",String.valueOf(abcd));*//*
sqLiteDB.close();*/
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
}
public void departureClick(View view) {
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
String depTime = getCurrentTime();
int stnId = listItemsDepp.getStnId();
String depClick = "departure";
String upSideKm = listItemsDepp.getStnUpsideKm();
String downsideKm = listItemsDepp.getStnDownSideKm();
sqLiteDB.open();
/*long abc = sqLiteDB.insertJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick);*/
/*long abcd = sqLiteDB.updateJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick,downsideKm,upSideKm);
Log.e("depclick",String.valueOf(abcd));*/
sqLiteDB.close();
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
}
public String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
Get the position of the row which is clicked and then set onclick false for positions less than clicked position
as follows:
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position));
for (int i = 0; i < position; i++) {
viewHolder.txtStnArr.setEnable(false);
}
notifyDataSetChanged();
}
});

AdapterView of Gridview is not refreshing, it is showing weird response (Some times it is refreshing some times not)

I am setting the adapter of gridview on a fragment. this fragment is attached on the layout of view pager and viewpager is attached in an activity.
I have checked my arraylist data is refreshed but view is not refreshing.
My code is:
Setting the adapter in the onCreate of Activity::
for(ArrayList<Item> newLst : updateList){
newPropertySubList.add(newLst);
}
Log.e("newPropertySubList","newPropertySubList"+newPropertySubList.size());
adapter = new PropertyPagerAdapetr(getSupportFragmentManager());
//propertyViewPager.setAdapter(adapter);
adapter.notifyChangeInPosition(1);
propertyViewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
mIndicator.setViewPager(propertyViewPager);
PropertyPagerAdapetr is: in this code section GridviewFragment new instance is created when adapter is setting.
public class PropertyPagerAdapetr extends FragmentPagerAdapter {
private long baseId = 0;
public PropertyPagerAdapetr(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
return GridViewFragment.newInstance(newPropertySubList.get(arg0));
}
#Override
public long getItemId(int position) {
return baseId + position;
}
public void destroyAllItem(){
getSupportFragmentManager().getFragments().clear();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if (newPropertySubList != null && newPropertySubList.size() > 0)
return newPropertySubList.size();
else
return 0;
}
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
GridViewFragment: Gridview adapter is setting in this fragment
public class GridViewFragment extends Fragment {
public static final String PROPERTY_TYPE = "property_type";
private GridView mImageGrid;
private View view;
ArrayList<Item> itemList;
String forRentOrSale;
double belowheight;
private GridLayout gLayout;
//int count;
//static Context mContext;
public static GridViewFragment newInstance(ArrayList<Item> propertyList) {
GridViewFragment frag = new GridViewFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("Property_item", propertyList);
frag.setArguments(bundle);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.grid_view_fragmnet, container, false);
mImageGrid = (GridView) rootView.findViewById(R.id.gridview);
itemList = (ArrayList<Item>) getArguments().getSerializable(
"Property_item");
LoadPropertyAdapter adapter = new LoadPropertyAdapter(getActivity());
mImageGrid.setAdapter(adapter);
//mImageGrid.setAdapter(new MyAdapter());
return rootView;
//return (view = inflater.inflate(R.layout.grid_view_fragmnet, null));
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
belowheight = (((SearchForm) getActivity()).belowHeight / 2);
initView();
initData();
setListener();
}
private void setListener() {
mImageGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Toast.makeText(getActivity(),
// ""+itemList.get(position).getPID()+" "+itemList.get(position).getA2(),
// Toast.LENGTH_LONG).show();
if (Constants.g_Setttings.getApp_google_analytics() != null
&& !Constants.g_Setttings.getApp_google_analytics().equals("")) {
TVApplication dApp = (TVApplication) getActivity().getApplication();
Tracker tracker = dApp.getTracker(TrackerName.APP_TRACKER,
Constants.g_Setttings.getApp_google_analytics());
tracker.setScreenName("/Search Form");
tracker.set(Fields.SCREEN_NAME, "Search Form");
tracker.send(new HitBuilders.AppViewBuilder().build());
}
Intent intent = new Intent(getActivity(),
PropertyDetailActivity.class);
Item item = itemList.get(position);
intent.putExtra(Constants.ACCESS_DETAIL_PAGE_KEY,
item);
if (((SearchForm) getActivity()).boolSale) {
intent.putExtra(PROPERTY_TYPE, "for sale");
} else if (((SearchForm) getActivity()).boolRent) {
intent.putExtra(PROPERTY_TYPE, "to rent");
} else if (((SearchForm) getActivity()).boolStudentRent) {
intent.putExtra(PROPERTY_TYPE, "to rent");
}
startActivity(intent);
}
});
}
private void initView() {
//mImageGrid = (GridView) view.findViewById(R.id.gridview);
// gLayout=(GridLayout) view.findViewById(R.id.gridlayout);
/*itemList = (ArrayList<Item>) getArguments().getSerializable(
"Property_item");
LoadPropertyAdapter adapter = new LoadPropertyAdapter();
mImageGrid.setAdapter(adapter);*/
}
private void initData() {
if (itemList == null || itemList.size() == 0)
return;
// setUpGridLayout();
/*
* ViewGroup.LayoutParams layoutParams = mImageGrid.getLayoutParams();
* layoutParams.height = (int)
* (((SearchForm)getActivity()).belowHeight/2); //this is in pixels
* mImageGrid.setLayoutParams(layoutParams);
*/
}
}
public class LoadPropertyAdapter extends BaseAdapter {
private Item propertyItem;
Context mContext;
Holder holder = null;
DisplayImageOptions options;
ImageLoader imageLoader;
ImageLoaderConfiguration config;
public LoadPropertyAdapter(FragmentActivity activity) {
mContext = activity;
imageLoader = ImageLoader.getInstance();
config = new ImageLoaderConfiguration.Builder(mContext)
.memoryCache(new WeakMemoryCache())
.denyCacheImageMultipleSizesInMemory()
.threadPoolSize(1)
.build();
options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.resetViewBeforeLoading()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
imageLoader.init(config);
}
#Override
public int getCount() {
if (itemList != null && itemList.size() > 0)
return itemList.size();
else
return 0;
}
#Override
public Object getItem(int arg0) {
return itemList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
public String imageUrl() {
String imageUrl = "";
/*
* if (nm_item.m_bIsAdvert) { imageUrl =
* Constants.advertContainer.getImages_url() + "&file=" +
* Constants.advertContainer.getGen_advert()
* .get(nm_item.m_nIndex).getsca_image(); } else {
*/
imageUrl = Constants.getRequestUrl(propertyItem.getPID(), 1,
Constants.FLOORPLANS_IMAGE_BIG_URL, "");
// }
return imageUrl;
}
public class Holder
{
TextView priceText,content, feesApply, cornerLabel;
ImageView imageview;
RelativeLayout propertyStatusBG, propertyInfoView, layout;
ProgressBar progressbar ;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = null;
propertyItem = itemList.get(position);
if (rowView == null) {
// If convertView is null then inflate the appropriate layout file
rowView = LayoutInflater.from(mContext).inflate( R.layout.grid_view_imageviewitem , null);
holder = new Holder();
rowView.setTag(holder);
}else{
holder = (Holder) rowView.getTag();
}
//rowView = new View(getActivity());
holder.imageview = (ImageView) rowView
.findViewById(R.id.img_property);
holder.priceText = (TextView) rowView
.findViewById(R.id.pricetext);
holder.content = (TextView) rowView
.findViewById(R.id.contenttext);
holder.feesApply = (TextView) rowView
.findViewById(R.id.txt_fees_rent);
holder.propertyStatusBG = (RelativeLayout) rowView
.findViewById(R.id.rel_status_bg);
holder.cornerLabel = (TextView) rowView
.findViewById(R.id.txt_property_offer);
holder.progressbar = (ProgressBar) rowView
.findViewById(R.id.progressbar);
holder.propertyInfoView = (RelativeLayout) rowView
.findViewById(R.id.property_info_view);
//holder.imageview.setTag(imageUrl());
if (Constants.filter_Parameter != null
&& (Constants.filter_Parameter.getGoal().equals("2")
|| Constants.filter_Parameter.getGoal().equals(
"3") || Constants.filter_Parameter
.getGoal().equals("5"))) {
if (Constants.g_Setttings != null
&& Constants.g_Setttings.getIncl_tenantfeesinfo() != null
&& Constants.g_Setttings.getIncl_tenantfeesinfo()
.equals("1")) {
if (propertyItem.getTenant_fee_exempt() != null
&& propertyItem.getTenant_fee_exempt().equals("0")) {
holder.feesApply.setVisibility(View.VISIBLE);
} else {
holder.feesApply.setVisibility(View.GONE);
}
} else {
holder.feesApply.setVisibility(View.GONE);
}
} else {
holder.feesApply.setVisibility(View.GONE);
}
if (holder.feesApply != null) {
holder.feesApply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
TenentFeeDialogActivity.class);
startActivity(intent);
}
});
}
Util.setButtonBackgroundColor(holder.propertyStatusBG);
// propertyStatusBG.getBackground().setAlpha(88);
Util.setButtonBackgroundColor(holder.cornerLabel);
if (propertyItem.getStatus() != null && !propertyItem.getStatus().equals("")) {
updatePropertyStatus(propertyItem.getStatus(), holder.cornerLabel,
holder.propertyStatusBG);
} else {
holder.propertyStatusBG.setVisibility(View.GONE);
}
if (propertyItem.getPR() != null
&& !propertyItem.getPR().equals("")) {
double price = Math.round(Double.parseDouble(propertyItem
.getPR()));
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMinimumFractionDigits(0);
format.setCurrency(Currency.getInstance(Locale.UK));
if (propertyItem.getLetRentFrequency() != null
&& !propertyItem.getLetRentFrequency().equals("")
&& (Constants.filter_Parameter.getGoal().equals("2") || Constants.filter_Parameter
.getGoal().equals("3"))) {
if (Constants.OPTIONS_FREQUENCY.equals("")) {
holder.priceText.setText(format.format(price) + " "
+ Constants.OPTIONS_FREQUENCY
);
} else {
holder.priceText.setText(format.format(price) + " "
+ propertyItem.getLetRentFrequency());
}
}
else if (Constants.g_Setttings.getApp_property_commercial() != null
&& Constants.g_Setttings.getApp_property_commercial()
.equals("1")) {
if ((Constants.g_Setttings
.getIncl_property_commercial_sales() != null && Constants.g_Setttings
.getIncl_property_commercial_sales().equals("1"))
|| Constants.g_Setttings
.getIncl_property_commercial_rent() != null
&& Constants.g_Setttings
.getIncl_property_commercial_rent().equals(
"1")) {
if (Constants.OPTIONS_FREQUENCY.equals("")) {
holder.priceText.setText(format.format(price) + " "
+ Constants.OPTIONS_FREQUENCY
);
} else {
holder.priceText.setText(format.format(price) + " "
+ propertyItem.getLetRentFrequency());
}
}
} else {
holder.priceText.setText(format.format(price));
}
}
String contentText = "";
String propertyTypeCode = propertyItem.getPT();
String propertyType = "";
if (propertyTypeCode != null && !propertyTypeCode.equals("")
&& !propertyTypeCode.equals("null")
&& !propertyTypeCode.equals("0")) {
if (Constants.propertyTypeList != null
&& Constants.propertyTypeList.size() > 0) {
for (int i = 0; i < Constants.propertyTypeList.size(); i++) {
if (Constants.propertyTypeList.get(i).getId() == Integer
.parseInt(propertyTypeCode)) {
propertyType = Constants.propertyTypeList.get(i)
.getLabel();
break;
}
}
} else {
propertyType = "";
}
} else {
propertyType = "";
}
initRentOrSale();
if (propertyItem.getBD() != null
&& !propertyItem.getBD().equals("")) {
if (propertyItem.getBD().equals("0")) {
if (!propertyType.equals("")) {
contentText = propertyType + " " + forRentOrSale + " ";
} else {
contentText = forRentOrSale + " ";
}
} else {
if (!propertyType.equals("")) {
contentText += propertyItem.getBD() + " bed "
+ propertyType + " " + forRentOrSale + " ";
} else {
contentText += propertyItem.getBD() + " bed "
+ forRentOrSale + " ";
}
}
}
if (propertyItem.getA2() != null
&& !propertyItem.getA2().equals("")) {
contentText += "in "
+ Html.fromHtml(StringEscapeUtils
.unescapeHtml(propertyItem.getA2())) + " ";
}
if (contentText != null && !contentText.equals("")) {
holder.content.setText(contentText);
}
imageLoader.displayImage(imageUrl(), holder.imageview,options, new ImageLoadingListener(){
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.progressbar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
holder.progressbar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
holder.progressbar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
holder.progressbar.setVisibility(View.GONE);
}
});
holder.layout = new RelativeLayout(getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
(int) (belowheight / 1.1));
holder.layout.addView(rowView, params);
holder.propertyInfoView.getLayoutParams().height = (int) (belowheight / 4.60);
return holder.layout;
}
}
}
Could be you're mixing GridLayout and GridView. They are different entities.
In setUpGridLayout() you are inflating a grid_view_imageviewitem and adding it to a GridLayout, not GridView.
*
i have solve the issue using
Handler disconnectHandler = new Handler() {
public void handleMessage(Message msg) {
}
};
Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
/////////// load data from here ////
}
}
};
disconnectHandler.postDelayed(disconnectCallback, 1000);*
*

Cannot use finish() inside Adapter

I'm always getting this error when i'm setting the finish method inside adapter.
11-28 09:46:09.661 8636-8646/? E/art: Failed sending reply to debugger: Broken pipe
11-28 09:46:17.709 8636-8636/com.juandirection E/InputEventReceiver: Exception dispatching input event.
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: java.lang.ClassCastException: com.juandirection.variables.Global cannot be cast to com.juandirection.ActivityCategorySelected
I tried to remove all item insde OnRatingChanged but the error remains the same.
public class AdapterPOI extends RecyclerView.Adapter<AdapterPOI.MainViewHolder> {
private List<ModelPoi> poiDatas;
private List<ModelImage> imageDatas;
private List<ModelComments> commentDatas;
private List<ModelFavorite> favoriteDatas;
private List<ModelAccounts> accountDatas;
private LayoutInflater inflater;
private Context context;
int viewType = 0;
int add;
int cCounter = 0;
int[] routeImg = {R.drawable.ic_resto_route, R.drawable.ic_sights_route, R.drawable.ic_transport_route, R.drawable.ic_hotel_route,
R.drawable.ic_gas_route, R.drawable.ic_school_route, R.drawable.ic_entertainment_route,
R.drawable.ic_shop_route, R.drawable.ic_atm_route, R.drawable.ic_bank_route, R.drawable.ic_hospital_route,
R.drawable.ic_pharmacy_route, R.drawable.ic_police_route, R.drawable.ic_toilet_route,};
public AdapterPOI(Context context, List<ModelPoi> poiDatas, List<ModelFavorite> favoriteDatas, List<ModelComments> commentDatas, List<ModelImage> imageDatas) {
inflater = LayoutInflater.from(context);
this.poiDatas = poiDatas;
this.context = context;
this.favoriteDatas = favoriteDatas;
this.imageDatas = imageDatas;
this.commentDatas = commentDatas;
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int listViewItemType = getItemViewType(viewType);
if (listViewItemType == 0) {
return new TitleHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_title, parent, false));
}
if (listViewItemType == 1 || listViewItemType == 4 || listViewItemType == 7) {
return new HeaderHolder(LayoutInflater.from(context).inflate(R.layout.headerinformation, parent, false));
}
if (listViewItemType == 2 || listViewItemType == 3 || listViewItemType == 6) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
}
if (listViewItemType == 5) {
return new GalleryHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_photos, parent, false));
}
if (listViewItemType == 8) {
return new RatingHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_rating, parent, false));
}
if (listViewItemType >= 9 && listViewItemType <= 8 + commentDatas.size()) {
return new CommentsHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_comments, parent, false));
}
if (listViewItemType == 14) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
}
if (listViewItemType >= 9 + commentDatas.size()) {
return new TapHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_taptorate, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
try {
if (position == 0) {
TitleHolder tHolder = (TitleHolder) holder;
tHolder.imgType.setBackgroundResource(routeImg[Global.getPosition]);
tHolder.txtTitle.setText(Global.selectedPOI);
ModelPoi poiData = (ModelPoi) getPOI(0);
tHolder.txtType.setText(poiData.POIType);
if (favoriteDatas.size() >= 1) {
tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
tHolder.txtID.setText("1");
} else {
tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white);
tHolder.txtID.setText("0");
}
float ratingBar = 0f;
for (int i = 0; i < commentDatas.size(); i++) {
ModelComments modelComments = (ModelComments) getComment(i);
ratingBar += Float.valueOf(modelComments.rating);
}
float finalRating;
finalRating = ratingBar / commentDatas.size();
tHolder.ratingBar.setRating(finalRating);
}
if (position == 1) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Information");
}
if (position == 2) {
MyViewHolder mHolder = (MyViewHolder) holder;
ModelPoi poiData = (ModelPoi) getPOI(0);
mHolder.icon.setImageResource(R.drawable.ic_information);
mHolder.title.setText(poiData.POIInfo);
mHolder.txtID.setText("0");
}
if (position == 3) {
MyViewHolder mHolder = (MyViewHolder) holder;
ModelPoi poiData = (ModelPoi) getPOI(0);
mHolder.icon.setImageResource(R.drawable.ic_place_black_36dp);
mHolder.title.setText(poiData.POIAddress);
mHolder.txtID.setText("1");
}
if (position == 4) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Photos");
}
if (position == 5) {
GalleryHolder gHolder = (GalleryHolder) holder;
AdapterGalleryViewPoi galleryViewAdapter;
galleryViewAdapter = new AdapterGalleryViewPoi(context, imageDatas);
gHolder.gallery.setAdapter(galleryViewAdapter);
final WindowManager display = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
display.getDefaultDisplay().getMetrics(metrics);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gHolder.gallery.getLayoutParams();
mlp.setMargins(-((metrics.widthPixels * 2 + 200) / 3), mlp.topMargin,
mlp.rightMargin, mlp.bottomMargin);
}
if (position == 6) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.icon.setImageResource(R.drawable.ic_local_see_black_24dp);
mHolder.title.setText("Add Photos");
mHolder.txtID.setText("2");
}
if (position == 7) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Reviews");
}
if (position == 8) {
RatingHolder mHolder = (RatingHolder) holder;
float ratingBar = 0f;
float getRate;
int progressbarE = 0, progressbarVG = 0, progressbarAVG = 0, progressbarP = 0, progressbarT = 0;
for (int i = 0; i < commentDatas.size(); i++) {
ModelComments modelComments = (ModelComments) getComment(i);
ratingBar += Float.valueOf(modelComments.rating);
getRate = Float.valueOf(modelComments.rating);
if (getRate >= 0 && getRate <= 1) {
progressbarT += getRate;
}
if (getRate > 1 && getRate <= 2) {
progressbarP += getRate;
}
if (getRate > 2 && getRate <= 3) {
progressbarAVG += getRate;
}
if (getRate > 3 && getRate <= 4) {
progressbarVG += getRate;
}
if (getRate > 4 && getRate <= 5) {
progressbarE += getRate;
}
}
mHolder.reviewTxt.setText(Global.selectedPOI);
float finalRatingBar;
finalRatingBar = ratingBar / commentDatas.size();
mHolder.ratingBarReview.setRating(finalRatingBar);
mHolder.progressbarE.setProgress(progressbarE);
mHolder.progressbarVG.setProgress(progressbarVG);
mHolder.progressbarAVG.setProgress(progressbarAVG);
mHolder.progressbarP.setProgress(progressbarP);
mHolder.progressbarT.setProgress(progressbarT);
}
if (position >= 9 && position <= 8 + commentDatas.size()) {
if (position == 9) {
cCounter = 0;
}
if (position == 10) {
cCounter = 1;
}
if (position == 11) {
cCounter = 2;
}
if (position == 12) {
cCounter = 3;
}
if (position == 13) {
cCounter = 4;
}
ModelComments modelComments = (ModelComments) getComment(cCounter);
CommentsHolder mHolder = (CommentsHolder) holder;
accountDatas = new Select().from(ModelAccounts.class)
.where(Condition.column(ModelAccounts$Table.GET_ID).is(modelComments.user_id)).queryList();
ModelAccounts modelAccounts = (ModelAccounts) getImg(0);
byte[] dataImg;
dataImg = Base64.decode(modelAccounts.img, Base64.DEFAULT);
Glide.with(context)
.load(dataImg)
.fitCenter()
.crossFade()
.into(mHolder.commentPhoto);
mHolder.commentTitle.setText(modelComments.title);
mHolder.commentDate.setText(modelComments.date);
mHolder.comments.setText(modelComments.comment);
mHolder.commentRatingbar.setRating(Float.valueOf(modelComments.rating));
mHolder.txtID.setText(modelComments.get_id);
}
if (commentDatas.size() == 5) {
if (position == 14) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.icon.setImageResource(R.drawable.ic_comment_black_24dp);
mHolder.title.setText("View More Comments");
mHolder.txtID.setText("3");
}
}
} catch (Exception e) {
Log.e("AdapterPOI", "" + e.toString());
}
}
public Object getImg(int position) {
return accountDatas.get(position);
}
public Object getPOI(int position) {
return poiDatas.get(position);
}
public Object getComment(int position) {
return commentDatas.get(position);
}
#Override
public int getItemCount() {
if (commentDatas.size() == 5) {
add = 16;
} else if (commentDatas.size() == 4) {
add = 14;
} else if (commentDatas.size() == 3) {
add = 13;
} else if (commentDatas.size() == 2) {
add = 12;
} else if (commentDatas.size() == 1) {
add = 11;
} else if (commentDatas.size() == 0) {
return add = 10;
}
return add;
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
viewType = 0;
} else if (position == 1) {
viewType = 1;
} else if (position == 2) {
viewType = 2;
} else if (position == 3) {
viewType = 3;
} else if (position == 4) {
viewType = 4;
} else if (position == 5) {
viewType = 5;
} else if (position == 6) {
viewType = 6;
} else if (position == 7) {
viewType = 7;
} else if (position == 8) {
viewType = 8;
} else if (position == 9) {
viewType = 9;
} else if (position == 10) {
viewType = 10;
} else if (position == 11) {
viewType = 11;
} else if (position == 12) {
viewType = 12;
} else if (position == 13) {
viewType = 13;
} else if (position == 14) {
viewType = 14;
} else if (position == 15) {
viewType = 15;
}
return viewType;
}
class MyViewHolder extends MainViewHolder {
TextView title, txtID;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.poiName);
txtID = (TextView) itemView.findViewById(R.id.txtID);
icon = (ImageView) itemView.findViewById(R.id.poiIcon);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getText = txtID.getText().toString();
String getTitle = title.getText().toString();
if (getText.equalsIgnoreCase("0")) {
Global.getInfo = getTitle;
Intent intent = new Intent(context, ViewInformation.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
if (getText.equalsIgnoreCase("1")) {
Log.e("Info", "Map");
}
if (getText.equalsIgnoreCase("2")) {
Log.e("Add Photo", "Add Photo");
}
if (getText.equalsIgnoreCase("3")) {
Global.getID = null;
Intent intent = new Intent(context, ViewComment.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
});
}
}
public class HeaderHolder extends MainViewHolder {
TextView txtInfo;
public HeaderHolder(View itemView) {
super(itemView);
this.txtInfo = (TextView) itemView.findViewById(R.id.txtinfo);
}
}
public class GalleryHolder extends MainViewHolder {
Gallery gallery;
public GalleryHolder(View itemView) {
super(itemView);
this.gallery = (Gallery) itemView.findViewById(R.id.gallery);
}
}
public class TapHolder extends MainViewHolder {
RatingBar ratingBar;
public TapHolder(View itemView) {
super(itemView);
this.ratingBar = (RatingBar) itemView.findViewById(R.id.tapToRate);
this.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Global.setRating = rating;
Intent intent = new Intent(context, ActivityReview.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//((ActivityCategorySelected)context).finish();
}
});
}
}
public class TitleHolder extends MainViewHolder {
ImageView imgType, imgFavorite;
TextView txtTitle, txtID, txtType;
RatingBar ratingBar;
public TitleHolder(View itemView) {
super(itemView);
final View view;
view = itemView;
imgType = (ImageView) itemView.findViewById(R.id.imgType);
imgFavorite = (ImageView) itemView.findViewById(R.id.imgFavorite);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtType = (TextView) itemView.findViewById(R.id.txtType);
txtID = (TextView) itemView.findViewById(R.id.txtID);
ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String getID = txtID.getText().toString();
final String getType = txtType.getText().toString();
if (Global.getUserId == null) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Sign In");
alertbox.setMessage("Please Sign in your account first.");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent = new Intent(context, ActivityLogin.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
} else {
if (getID.equals("0")) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Add This place to your Favorites?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if (CheckNetwork.isNetworkAvailable(context)) {
txtID.setText("1");
imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
addToFavorite(getType);
Thread timerThread = new Thread() {
public void run() {
try {
new DatabaseAsyncFavorites(context).execute();
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timerThread.start();
} else {
Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Remove this place from your Favorites?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if (CheckNetwork.isNetworkAvailable(context)) {
addToFavorite(getType);
new Delete()
.from(ModelFavorite.class)
.where(Condition.column(ModelFavorite$Table.USER_ID).is(Global.getUserId))
.and(Condition.column(ModelFavorite$Table.LATITUDE).is(Global.lat)).query();
txtID.setText("0");
imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white_nav);
} else {
Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
}
}
}
});
}
}
public void addToFavorite(final String getType) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST, Global.INSERT_FAV_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("latitude", Global.lat);
parameters.put("user_id", Global.getUserId);
parameters.put("type", getType);
return parameters;
}
};
requestQueue.add(request);
}
public class RatingHolder extends MainViewHolder {
TextView reviewTxt;
RatingBar ratingBarReview;
ProgressBar progressbarE, progressbarVG, progressbarAVG, progressbarP, progressbarT;
public RatingHolder(View itemView) {
super(itemView);
this.reviewTxt = (TextView) itemView.findViewById(R.id.reviewTxt);
this.ratingBarReview = (RatingBar) itemView.findViewById(R.id.ratingBarReview);
this.progressbarE = (ProgressBar) itemView.findViewById(R.id.progressbarE);
this.progressbarVG = (ProgressBar) itemView.findViewById(R.id.progressbarVG);
this.progressbarAVG = (ProgressBar) itemView.findViewById(R.id.progressbarAVG);
this.progressbarP = (ProgressBar) itemView.findViewById(R.id.progressbarP);
this.progressbarT = (ProgressBar) itemView.findViewById(R.id.progressbarT);
}
}
public class CommentsHolder extends MainViewHolder {
ImageView commentPhoto;
TextView commentTitle, commentDate, comments, txtID;
RatingBar commentRatingbar;
public CommentsHolder(View itemView) {
super(itemView);
this.commentPhoto = (ImageView) itemView.findViewById(R.id.commentPhoto);
this.commentTitle = (TextView) itemView.findViewById(R.id.commentTitle);
this.commentDate = (TextView) itemView.findViewById(R.id.commentDate);
this.comments = (TextView) itemView.findViewById(R.id.comments);
this.txtID = (TextView) itemView.findViewById(R.id.txtID);
this.commentRatingbar = (RatingBar) itemView.findViewById(R.id.commentRatingbar);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Global.getID = txtID.getText().toString();
Intent intent = new Intent(context, ViewComment.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
}
public class MainViewHolder extends RecyclerView.ViewHolder {
public MainViewHolder(View itemView) {
super(itemView);
}
}
}
I don't know what's causing the problem. I can use the same method on my fragments but in this adapter it's not working.
Change
adapter = new AdapterPOI(getApplicationContext(), ....)
to
adapter = new AdapterPOI(this, ....)
in the code where you call the adapter's constructor. You get the error because getApplicationContext() cannot be casted to an ActivityCategorySelected. That's an Application context; whereas the adapter is expecting an Activity's context.

Memory leak when drag PullToRefresh ListView

The problem is that when i stretch up the pullToRefreshLiew (similar to listview), the memory the application occupy will be increasing step by step. I have tried many methods from the internet, but the bug still exists.
When i stretch up the pullToRefreshLiew, the memory will increasing to 90m
from 50m gradually.
Here is my memory monitor:
Here is my code below: (I omit the import code)
if you need my xml code,i will paste them as well.I am very grateful to you for your help.
public class YuerjingActivity extends CommonActivity implements View.OnClickListener {
private RelativeLayout back;
private int baseid;
private PullToRefreshListView pullToRefreshListView;
private ArrayList<ForumListItem> forumListItems = new ArrayList<ForumListItem>();
private MyAdapter myAdapter;
private LinearLayout noTip;
private RelativeLayout postForum;
static class ViewHolder1 {
TextView title;
TextView line;
}
static class ViewHolder2 {
private ImageView avatar;
private TextView name;
private TextView time;
private ImageView huo;
private ImageView jing;
private TextView title;
private LinearLayout pics;
private ImageView img1;
private ImageView img2;
private ImageView img3;
private ImageView img4;
private TextView replynum;
}
protected class MyAdapter extends BaseAdapter {
public MyAdapter() {
}
public int getCount() {
return forumListItems.size();
}
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int t = getItemViewType(position);
ViewHolder1 viewHolder1 = null;
ViewHolder2 viewHolder2 = null;
ForumListItem forumListItem = forumListItems.get(position);
if (convertView == null) {
if (t == 1) {
convertView = getLayoutInflater().inflate(R.layout.item_top, null);
viewHolder1 = new ViewHolder1();
viewHolder1.title = (TextView) convertView.findViewById(R.id.title);
viewHolder1.line = (TextView) convertView.findViewById(R.id.top_line);
convertView.setTag(viewHolder1);
} else {
convertView = getLayoutInflater().inflate(R.layout.common_forum_item, null);
viewHolder2 = new ViewHolder2();
viewHolder2.avatar = (ImageView) convertView.findViewById(R.id.avatar);
viewHolder2.name = (TextView) convertView.findViewById(R.id.name);
viewHolder2.time = (TextView) convertView.findViewById(R.id.time);
viewHolder2.jing = (ImageView) convertView.findViewById(R.id.jing);
viewHolder2.huo = (ImageView) convertView.findViewById(R.id.huo);
viewHolder2.pics = (LinearLayout) convertView.findViewById(R.id.pics);
viewHolder2.img1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder2.img2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder2.img3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder2.img4 = (ImageView) convertView.findViewById(R.id.img4);
viewHolder2.replynum = (TextView) convertView.findViewById(R.id.replynum);
viewHolder2.title = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(viewHolder2);
}
} else {
if (t == 1) {
viewHolder1 = (ViewHolder1) convertView.getTag();
} else {
viewHolder2 = (ViewHolder2) convertView.getTag();
}
}
if (t == 1) {
viewHolder1.title.setText(forumListItem.getTitle());
if (position + 1 < getCount()) {
if (forumListItems.get(position + 1).getIs_top() == 0) {
viewHolder1.line.setVisibility(View.VISIBLE);
} else {
viewHolder1.line.setVisibility(View.GONE);
}
} else {
viewHolder1.line.setVisibility(View.GONE);
}
} else {
if (forumListItem.getAvatar() == null) {
viewHolder2.avatar.setImageResource(R.drawable.user);
} else {
ImageLoader.getInstance().displayImage(forumListItem.getAvatar(), viewHolder2.avatar, UIL.getOption3());
}
viewHolder2.name.setText(forumListItem.getName());
viewHolder2.time.setText(DateUtils.toNow(forumListItem.getTime()));
viewHolder2.title.setText(forumListItem.getTitle());
if (forumListItem.getIs_hot() == 1) {
viewHolder2.huo.setVisibility(View.VISIBLE);
} else {
viewHolder2.huo.setVisibility(View.GONE);
}
if (forumListItem.getIs_rec() == 1) {
viewHolder2.jing.setVisibility(View.VISIBLE);
} else {
viewHolder2.jing.setVisibility(View.GONE);
}
viewHolder2.replynum.setText(forumListItem.getReplynum());
viewHolder2.img1.setVisibility(View.GONE);
viewHolder2.img2.setVisibility(View.GONE);
viewHolder2.img3.setVisibility(View.GONE);
viewHolder2.img4.setVisibility(View.GONE);
for (int i = 0; i < forumListItem.pics.size(); i++) {
if (i == 0) {
viewHolder2.pics.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img1, UIL.getOptions(R.drawable.info_head));
viewHolder2.img1.setVisibility(View.VISIBLE);
}
if (i == 1) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img2, UIL.getOptions(R.drawable.info_head));
viewHolder2.img2.setVisibility(View.VISIBLE);
}
if (i == 2) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img3, UIL.getOptions(R.drawable.info_head));
viewHolder2.img3.setVisibility(View.VISIBLE);
}
if (i == 3) {
ImageLoader.getInstance().displayImage(forumListItem.pics.get(i), viewHolder2.img4, UIL.getOptions(R.drawable.info_head));
viewHolder2.img4.setVisibility(View.VISIBLE);
}
}
}
return convertView;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return forumListItems.get(position).getIs_top();
}
}
private static class ForumListItem {
private String avatar;
private String name;
private String time;
private int is_hot;
private int is_rec;
private int has_pic;
private int is_top;
private String title;
private String replynum;
private int id;
public ArrayList<String> pics = new ArrayList<String>();
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getIs_top() {
return is_top;
}
public void setIs_top(int is_top) {
this.is_top = is_top;
}
public int getHas_pic() {
return has_pic;
}
public void setHas_pic(int has_pic) {
this.has_pic = has_pic;
}
public int getIs_rec() {
return is_rec;
}
public void setIs_rec(int is_rec) {
this.is_rec = is_rec;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getReplynum() {
return replynum;
}
public void setReplynum(String replynum) {
this.replynum = replynum;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yuerjing);
init();
}
private void init() {
back = generateFindViewById(R.id.back);
back.setOnClickListener(this);
baseid = 0;
noTip = generateFindViewById(R.id.notip);
pullToRefreshListView = generateFindViewById(R.id.quanzi);
myAdapter = new MyAdapter();
pullToRefreshListView.setAdapter(myAdapter);
pullToRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
pullToRefreshListView.setOnRefreshListener(new MyOnRefreshListener2());
pullToRefreshListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (HttpUtil.isNetworkConnected(getApplicationContext())) {
Intent intent = new Intent(YuerjingActivity.this, NewForumActivity.class);
intent.putExtra("postid", forumListItems.get(position - 1).getId());
startActivity(intent);
} else {
}
}
});
postForum = generateFindViewById(R.id.xiexie);
postForum.setOnClickListener(this);
getList("new");
}
class MyOnRefreshListener2 implements PullToRefreshBase.OnRefreshListener2<ListView> {
public MyOnRefreshListener2() {
}
#Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
getList("new");
}
#Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
getList("old");
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
private void getList(final String dir) {
if (HttpUtil.isNetworkConnected(getApplicationContext())) {
RequestQueue m_queue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
String param = "";
String url = "";
try {
if (UserInfo.getInstance().getHaslogin(getApplicationContext()) == -1 || UserInfo.getInstance().getHaslogin(getApplicationContext()) == 0) {
object.put("uid", 0);
} else {
object.put("uid", UserInfo.getInstance().getUserId(getApplicationContext()));
object.put("token", UserInfo.getInstance().getAccessToken(getApplicationContext()));
}
object.put("utype", 1);
object.put("posttype", "2");
object.put("classid", "0");
object.put("pagesize", 10);
object.put("dir", dir);
if (!dir.equals("new")) {
object.put("baseid", baseid);
}
param = object.toString();
url = Rpc.m_rpc_url + "&message=" + "USER_GET_ARTICLES3" + "&data=" + java.net.URLEncoder.encode(param, "utf-8");
System.err.println(url);
System.err.println(baseid);
} catch (Exception e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String result = response.toString();
JSONObject indexData = Utils.getInfoJsonObject(result);
boolean flag = indexData.getBoolean("ret");
int flagCode = indexData.getInt("retCode");
if (!flag) {
} else {
if (flagCode == 1) {
if (dir.equals("new")) {
forumListItems.clear();
baseid = 0;
}
String avatar_header = indexData.getString("avatar_header");
JSONArray jsonArray = indexData.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
ForumListItem forumListItem = new ForumListItem();
if (jsonArray.getJSONObject(i).getString("author_avatar").equals("null") || jsonArray.getJSONObject(i).getString("author_avatar") == null) {
forumListItem.setAvatar(null);
} else {
forumListItem.setAvatar(avatar_header + jsonArray.getJSONObject(i).getString("author_avatar"));
}
forumListItem.setName(jsonArray.getJSONObject(i).getString("author_name"));
forumListItem.setTime(jsonArray.getJSONObject(i).getString("post_time"));
forumListItem.setReplynum(jsonArray.getJSONObject(i).getString("replynum"));
forumListItem.setTitle(jsonArray.getJSONObject(i).getString("title"));
forumListItem.setId(jsonArray.getJSONObject(i).getInt("id"));
if (jsonArray.getJSONObject(i).getInt("is_hot") == 1) {
forumListItem.setIs_hot(1);
} else {
forumListItem.setIs_hot(0);
}
if (jsonArray.getJSONObject(i).getInt("has_pic") == 1) {
forumListItem.setHas_pic(1);
} else {
forumListItem.setHas_pic(0);
}
if (jsonArray.getJSONObject(i).getInt("is_rec") == 1) {
forumListItem.setIs_rec(1);
} else {
forumListItem.setIs_rec(0);
}
if (jsonArray.getJSONObject(i).getInt("is_top") == 1) {
forumListItem.setIs_top(1);
} else {
forumListItem.setIs_top(0);
}
if (forumListItem.getHas_pic() == 1 && jsonArray.getJSONObject(i).has("pics")) {
JSONArray pics = jsonArray.getJSONObject(i).getJSONArray("pics");
for (int j = 0; j < pics.length(); j++) {
forumListItem.pics.add(avatar_header + pics.getJSONObject(j).getString("srcurl"));
}
}
forumListItems.add(forumListItem);
}
}else {
Toast.makeText(getApplicationContext(), "retCode=" + flagCode, Toast.LENGTH_SHORT).show();
}
myAdapter.notifyDataSetChanged();
pullToRefreshListView.onRefreshComplete();
if (forumListItems.size() > 0 && forumListItems.get(forumListItems.size() - 1).getIs_top() == 0) {
baseid = forumListItems.get(forumListItems.size() - 1).getId();
} else {
baseid = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pullToRefreshListView.onRefreshComplete();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
m_queue.add(jsonObjectRequest);
m_queue.start();
} else {
pullToRefreshListView.postDelayed(new Runnable() {
#Override
public void run() {
pullToRefreshListView.onRefreshComplete();
}
}, 500);
}
}
}

Categories

Resources