How to disable previous items in a ListView - android

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

Related

ListView repeating the data on load more

I am using on scroll to load more data and show them in list view but my ListView first shows already loaded data then adds the newly added data to ListView
I have used for reference this and many others but unable to solve the issue
Here is my activity class
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
ButterKnife.bind(this);
Users = Users.getCurrentUser(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
UIUtility.setStatusColor(this);
Intent intent = getIntent();
try {
entityData = new JSONArray(intent.getStringExtra(EXTRA_DATA));
} catch (JSONException e) {
e.printStackTrace();
}
viewAllCategory = intent.getIntExtra(EXTRA_CATEGORY, 0);
viewAllEntityType = intent.getIntExtra(EXTRA_TYPE, 0);
latitude = intent.getDoubleExtra(EXTRA_LATITUDE, 0);
longitude = intent.getDoubleExtra(EXTRA_LONGITUDE, 0);
setTitle(TITLES[viewAllCategory]);
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser = new ViewAllUserAdapter(this, users);
lvEntity.setAdapter(adapterUser);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook = new ViewAllBookAdapter(this, books);
lvEntity.setAdapter(adapterBook);
}
lvEntity.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!stopLoadingMore) {
if (totalItemCount == firstVisibleItem + visibleItemCount && !isLoading) {
isLoading = true;
showLoading();
loadMoreData();
}
}
}
});
}
private void loadMoreData() {
String loadMoreUrl = buildLoadMoreUrl();
ShareMyBookHttpClient client = new ShareMyBookHttpClient();
client.get(loadMoreUrl, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
hideLoading();
if (responseBody != null) {
start = start+20;
try {
JSONObject jo = new JSONObject(new String(responseBody));
if (!jo.getBoolean(Constants.JsonKeys.ERROR)) {
JSONArray data = jo.getJSONArray(Constants.JsonKeys.DATA);
if (data.length() == 0) {
stopLoadingMore = true;
return;
}
if (data.length() < 20) {
stopLoadingMore = true;
}
for (int i = 0; i < data.length(); i++) {
entityData.put(data.getJSONObject(i));
}
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser.mergeArray(users);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook.mergeArray(books);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
hideLoading();
}
});
}
private String buildLoadMoreUrl() {
switch (viewAllCategory) {
default:
case ViewAllCategory.CATEGORY_USER:
return Constants.createUrlToGetViewAllUsers(Users.getId(), latitude, longitude, Users.getAuthToken(), start, LIMIT);
case ViewAllCategory.CATEGORY_MY_BOOKS:
return Constants.createUrlToGetViewAllMyBooks(Users.getId(), Users.getAuthToken(), start, LIMIT);
}
}
private void showLoading() {
sbLoading = Snackbar.make(coolMain, R.string.view_all_loading, Snackbar.LENGTH_INDEFINITE);
sbLoading.show();
}
private void hideLoading() {
isLoading = false;
if (sbLoading != null) {
sbLoading.dismiss();
}
}
and following is my AdapterClasss
public class ViewAllUserAdapter extends BaseAdapter {
private List<Users> users;
private Context context;
public ViewAllUserAdapter(Context context, List<Users> usersData) {
this.context = context;
users = usersData;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
}
return row;
}
#Override
public int getCount() {
return users == null ? 0 : users.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
public class UserVH extends View {
#Bind(R.id.item_vau_iv_user_image)
ImageView ivUserImage;
#Bind(R.id.item_vau_tv_name)
TextView tvName;
#Bind(R.id.item_vau_tv_distance)
TextView tvDistance;
private int position;
public UserVH(View view, final int position) {
super(context);
this.position = position;
ButterKnife.bind(this, view);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
UIUtility.openUserDetailActivity(context, users.get(position));
}
});
}
}
}
As you already referred this link, Exactly the same issue is happening with you, You should have correct implementation for holder class in getView method.
Update your getView() method as per below :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();
}
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
return row;
}
And update your getItemId and getItem methods as per below :
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
EDIT : clear the list additional users before adding the new objects
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
// Following line to be added
additonalusers.clear();
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
Your implementation of following methods is incorrect.
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
Change them as below
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}

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

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

Android RecycleView adapter sometime doesnt call

I have an issue in RecycleView. My screen has two tabs, both tabs contain recycleview.It call normally most of the time but sometimes give empty screen. Just I wrote log & system.out and found this issue. I will paste my adapter class code here.
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
List<ContentTitle> titles;
Context context;
private List<Item> titleData = new ArrayList<Item>();
public ExpandableListAdapter(List<Item> data) {
this.titleData = data;
System.out.println("===this.titleData===" + this.titleData.size());
}
public void replaceContentFragment(String title,int id,int bookmarked) {
try {
SkillsApp SkillsApp = (SkillsApp) context.getApplicationContext();
Fragment fragment = new ContentActivityFragment();
FragmentManager fragmentManager = skillsUSAApp.mainActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
SkillsApp.subtitleID = id;
SkillsApp.isbookmark = (bookmarked == 0)? false:true;
SkillsApp.mainActivity.getSupportActionBar().setTitle(title);
SkillsApp.selectedSubtitleID = id;
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
try{
context = parent.getContext();
final SkillsApp skillsApp = (SkillsAApp)context.getApplicationContext();
if(!skillsApp.isDrawer){
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.main_title, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
LayoutInflater inflater1 = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater1.inflate(R.layout.sub_title, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Child", "child");
TextView text = (TextView) view.findViewById(R.id.header_title);
}
});
return new RecyclerView.ViewHolder(view) {
};
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try{
System.out.println("==========##########");
final Item item = titleData.get(position);
final SkillsAApp skillsAApp = (SkillsAApp)context.getApplicationContext();
System.out.println("===onBindViewHolder item===" + item.mainTitle.title);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.mainTitle.title);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
}
itemController.layoutItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(!skillsAApp.isDrawer){
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = titleData.indexOf(itemController.refferalItem);
while (titleData.size() > pos + 1 && titleData.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(titleData.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
int pos = titleData.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
titleData.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.down_arrow);
item.invisibleChildren = null;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
case CHILD:
View itemTextView = (View) holder.itemView;
TextView view = (TextView) itemTextView.findViewById(R.id.header_title);
view.setText(titleData.get(position).subtitle.title);
final int pos = position;
itemTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(!skillsUSAApp.isDrawer){
TextView text = (TextView) view.findViewById(R.id.header_title);
FlurryAgent.logEvent("Sub Category Item");
replaceContentFragment(text.getText().toString(), titleData.get(pos).subtitle.subtitleId, titleData.get(pos).subtitle.bookMarked);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public int getItemViewType(int position) {
return titleData.get(position).type;
}
#Override
public int getItemCount() {
return titleData.size();
}
#Override
public long getItemId(int position) {
return position;
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public RelativeLayout layoutItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
try{
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
layoutItem = (RelativeLayout) itemView.findViewById(R.id.ll_title);
}catch (Exception e){
e.printStackTrace();
}
}
}
public static class Item {
public int type;
public String text;
public ContentTitle mainTitle;
public ContentSubTitle subtitle;
public List<Item> invisibleChildren;
public Item(int type, String text, List<Item> children) {
this.type = type;
this.text = text;
this.invisibleChildren = children;
}
public Item(int type, ContentTitle title,ContentSubTitle stitle) {
this.type = type;
this.mainTitle = title;
this.subtitle=stitle;
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
Here is a calling adapter from tab fragment
recyclerview = (RecyclerView) v.findViewById(R.id.recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext(), LinearLayoutManager.VERTICAL, false));
// recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext()));
ExpandableListAdapter adapter = new ExpandableListAdapter(items);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
could you please advice me what is an issue? I didn't get any console error message.Could you please help me anyone here

Android Listview Overwrite data instead of append

In my Android application, I am using webservices with index values (for eg.
https://mysampleurl.com/sampledata?username=""&&password=""&&startindex="1"&&endindex="10")
and pass the extracted data to a BaseAdapter via an arraylist and display the result in a listview.
When the listview reaches the bottom, Using asynctask I will increment the index values (for eg.
https://mysampleurl.com/sampledata?username=""&&password=""&&startindex="11"&&endindex="20").
I will receive the data and store it in arraylist and it goes on.
But when I pass array list values to adapter, it overwrites the existing data instead of appending with previous values.
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
System.out.println("position:"+position);
}
I have checked this above code in some other examples, at first it gives values like 1,2,.....10. and at second time it gives 1,2,3,.....20. But in my application it always return the values upto 1,2,3......10.
Could some one tell me what mistake I have done?
public ContentListAdapter (Context context, ArrayList<CommonData> contentList)
{
ctxt = context;
this.ContentList = contentList;
contentListRowInflater = LayoutInflater.from(context);
mSelectedItemsIds=new SparseBooleanArray();
checkBoxState=new boolean[contentList.size()];
}
#Override
public int getCount() {
return (filteredContentList == null)?0:filteredContentList.size();
}
#Override
public Object getItem(int position) {
return filteredContentList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
Here only i pass the values and check the position
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ContentListActivity.adapterFlag = false;
DocumentListViewHolder viewHolder = null;
if (convertView == null || convertView.getTag() == null) {
convertView = contentListRowInflater.inflate(
R.layout.content_list_row, null);
viewHolder = new DocumentListViewHolder();
viewHolder.ivDocumentdoctypeIcon = (ImageView) convertView.findViewById(R.id.ivDocumentTypeIcon);
viewHolder.tvDocumentTitle = (TextView) convertView.findViewById(R.id.tvDocumentTitle);
viewHolder.tvsubitemcount = (TextView) convertView.findViewById(R.id.tvsubitemcount);
viewHolder.ivarrowlauncher = (ImageView)convertView.findViewById(R.id.arrowlauncher);
viewHolder.checkboxselection=(CheckBox)convertView.findViewById(R.id.checkboxdeletion);
checkBoxSelection=viewHolder.checkboxselection;
viewHolder.checkboxselection.setChecked(checkBoxState[position]);
viewHolder.ivarrowlauncher = (ImageView)convertView.findViewById(R.id.arrowlauncher);
mainlayoutrl = (RelativeLayout)convertView.findViewById(R.id.clrrlmain);
sublayoutll = (LinearLayout)convertView.findViewById(R.id.clrowll);
arrowlayoutll = (LinearLayout)convertView.findViewById(R.id.clarrowll);
final Context context = ContentListActivity.contentListActivity;
if(viewHolder.checkboxselection.isChecked()) {
mainlayoutrl.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
sublayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
arrowlayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.checkboxrowselect));
} else {
mainlayoutrl.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
sublayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
arrowlayoutll.setBackgroundColor(ctxt.getResources().getColor(R.color.white));
}
sublayoutll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Config.networkConnectionCheck(context)) {
if(filteredContentList.get(position).type.equalsIgnoreCase("FOLDER")) {
ContentListActivity.ListarrowClick(position+1,context);
} else if (refreshFlag == false) {
ContentListActivity.oldviewContent(position+1,context);
} else
} else {
ContentListActivity.oldofflineViewContent(position+1,context);
}
}
});
arrowlayoutll.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
ContentListActivity.ListarrowClick(position+1,context);
}
});
viewHolder.ivfilesDownload=(ImageView)convertView.findViewById(R.id.document_list_row_download_imageview);
//newly added by venkat
viewHolder.ivfilesdownloaded=(ImageView)convertView.findViewById(R.id.document_list_row_downloaded_imageview);
viewHolder.tvDocumentDescription=(TextView)convertView.findViewById(R.id.tvdocumentdescription);
} else {
viewHolder = (DocumentListViewHolder) convertView.getTag();
}
viewHolder.tvDocumentTitle.setText(filteredContentList.get(position).name);
String desc = filteredContentList.get(position).versiondescription;
if (desc != null) {
viewHolder.tvDocumentDescription.setText(filteredContentList
.get(position).versiondescription);
}
String doctype = filteredContentList.get(position).type;
String subitemcount = filteredContentList.get(position).subitemcount;
if (doctype.equalsIgnoreCase(ctxt.getResources()
.getString(R.string.pdf))) {
viewHolder.ivDocumentdoctypeIcon
.setImageResource(R.drawable.pdfbigicon);
} else if (doctype.equalsIgnoreCase(ctxt.getResources().getString(
R.string.swf))) {
viewHolder.ivDocumentdoctypeIcon
.setImageResource(R.drawable.flashbigicon);
} if(doctype.equalsIgnoreCase(ctxt.getResources().getString(
R.string.folder)))
{
viewHolder.ivarrowlauncher.setVisibility(View.INVISIBLE);
}
if (filteredContentList.get(position).isupdateavailable
.equalsIgnoreCase(ctxt.getResources().getString(
R.string.update_false_status))) {
} else if (filteredContentList.get(position).isupdateavailable
.equalsIgnoreCase(ctxt.getResources().getString(
R.string.update_true_status))) {
WebAPI webapi = new WebAPI(ctxt);
if (LoginHandler.arraylistdata.size() == 1) {
user_id = LoginHandler.arraylistdata.get(0)
.getUserid();
org_id = LoginHandler.arraylistdata.get(0)
.getOrgId();
} else {
user_id = LoginHandler.arraylistdata.get(
OrgListActivity.selected_org_pos)
.getUserid();
org_id = LoginHandler.arraylistdata.get(
OrgListActivity.selected_org_pos)
.getOrgId();
}
LoginDatabaseHandler loginDBHandler = new LoginDatabaseHandler(
ctxt);
loginDBHandler.open();
int toglState = loginDBHandler.checkOffToggleState(
user_id, org_id, filteredContentList
.get(position).dockey.toString());
}
} else
versionUpdate(position, ctxt);
}
});
}
/*ends*/
return convertView;
}

hide section labels in listview

I use component android-section-list (http://code.google.com/p/android-section-list/) to create sections in my listView. How can I hide sections after push some button?
I try to do like
public void onClick(View v) {
switch(v.getId()) {
case R.id.sortTitle:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.market_list_separator, null, false);
TextView separatorLayout = (TextView) convertView.findViewById(R.id.section_view);
separatorLayout.setVisibility(View.GONE);
sectionAdapter.notifyDataSetChanged();
setButtonState(sortByTitle);
adapter.sort((Comparator<SectionListItem>) sortByTitle());
break;
}
}
But this way don't work.
My adapter put data in list rows and SectionListAdapter draw sections.
public class SectionListAdapter extends BaseAdapter implements ListAdapter,
OnItemClickListener {
private final DataSetObserver dataSetObserver = new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
updateSessionCache();
}
#Override
public void onInvalidated() {
super.onInvalidated();
updateSessionCache();
};
};
private final ListAdapter linkedAdapter;
private final Map<Integer, String> sectionPositions = new LinkedHashMap<Integer, String>();
private final Map<Integer, Integer> itemPositions = new LinkedHashMap<Integer, Integer>();
private final Map<View, String> currentViewSections = new HashMap<View, String>();
private int viewTypeCount;
protected final LayoutInflater inflater;
private View transparentSectionView;
private OnItemClickListener linkedListener;
public SectionListAdapter(final LayoutInflater inflater,
final ListAdapter linkedAdapter) {
this.linkedAdapter = linkedAdapter;
this.inflater = inflater;
linkedAdapter.registerDataSetObserver(dataSetObserver);
updateSessionCache();
}
private boolean isTheSame(final String previousSection,
final String newSection) {
if (previousSection == null) {
return newSection == null;
} else {
return previousSection.equals(newSection);
}
}
private synchronized void updateSessionCache() {
int currentPosition = 0;
sectionPositions.clear();
itemPositions.clear();
viewTypeCount = linkedAdapter.getViewTypeCount() + 1;
String currentSection = null;
final int count = linkedAdapter.getCount();
for (int i = 0; i < count; i++) {
final SectionListItem item = (SectionListItem) linkedAdapter
.getItem(i);
if (!isTheSame(currentSection, item.section)) {
sectionPositions.put(currentPosition, item.section);
currentSection = item.section;
currentPosition++;
}
itemPositions.put(currentPosition, i);
currentPosition++;
}
}
public synchronized int getCount() {
return sectionPositions.size() + itemPositions.size();
}
public synchronized Object getItem(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
final int linkedItemPosition = getLinkedPosition(position);
return linkedAdapter.getItem(linkedItemPosition);
}
}
public synchronized boolean isSection(final int position) {
return sectionPositions.containsKey(position);
}
public synchronized String getSectionName(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
return null;
}
}
public long getItemId(final int position) {
if (isSection(position)) {
return sectionPositions.get(position).hashCode();
} else {
return linkedAdapter.getItemId(getLinkedPosition(position));
}
}
protected Integer getLinkedPosition(final int position) {
return itemPositions.get(position);
}
#Override
public int getItemViewType(final int position) {
if (isSection(position)) {
return viewTypeCount - 1;
}
return linkedAdapter.getItemViewType(getLinkedPosition(position));
}
private View getSectionView(final View convertView, final String section) {
View theView = convertView;
if (theView == null) {
theView = createNewSectionView();
}
setSectionText(section, theView);
replaceSectionViewsInMaps(section, theView);
return theView;
}
protected void setSectionText(final String section, final View sectionView) {
final TextView textView = (TextView) sectionView.findViewById(R.id.listTextView);
textView.setText(section);
}
protected synchronized void replaceSectionViewsInMaps(final String section,
final View theView) {
if (currentViewSections.containsKey(theView)) {
currentViewSections.remove(theView);
}
currentViewSections.put(theView, section);
}
protected View createNewSectionView() {
return inflater.inflate(R.layout.section_view, null);
}
public View getView(final int position, final View convertView,
final ViewGroup parent) {
if (isSection(position)) {
return getSectionView(convertView, sectionPositions.get(position));
}
return linkedAdapter.getView(getLinkedPosition(position), convertView,
parent);
}
#Override
public int getViewTypeCount() {
return viewTypeCount;
}
#Override
public boolean hasStableIds() {
return linkedAdapter.hasStableIds();
}
#Override
public boolean isEmpty() {
return linkedAdapter.isEmpty();
}
#Override
public void registerDataSetObserver(final DataSetObserver observer) {
linkedAdapter.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
linkedAdapter.unregisterDataSetObserver(observer);
}
#Override
public boolean areAllItemsEnabled() {
return linkedAdapter.areAllItemsEnabled();
}
#Override
public boolean isEnabled(final int position) {
if (isSection(position)) {
return true;
}
return linkedAdapter.isEnabled(getLinkedPosition(position));
}
public void makeSectionInvisibleIfFirstInList(final int firstVisibleItem) {
final String section = getSectionName(firstVisibleItem);
// only make invisible the first section with that name in case there
// are more with the same name
boolean alreadySetFirstSectionIvisible = false;
for (final Entry<View, String> itemView : currentViewSections
.entrySet()) {
if (itemView.getValue().equals(section)
&& !alreadySetFirstSectionIvisible) {
itemView.getKey().setVisibility(View.INVISIBLE);
alreadySetFirstSectionIvisible = true;
} else {
itemView.getKey().setVisibility(View.VISIBLE);
}
}
for (final Entry<Integer, String> entry : sectionPositions.entrySet()) {
if (entry.getKey() > firstVisibleItem + 1) {
break;
}
setSectionText(entry.getValue(), getTransparentSectionView());
}
}
public synchronized View getTransparentSectionView() {
if (transparentSectionView == null) {
transparentSectionView = createNewSectionView();
}
return transparentSectionView;
}
protected void sectionClicked(final String section) {
//
}
public void onItemClick(final AdapterView< ? > parent, final View view,
final int position, final long id) {
if (isSection(position)) {
sectionClicked(getSectionName(position));
} else if (linkedListener != null) {
linkedListener.onItemClick(parent, view,
getLinkedPosition(position), id);
}
}
public void setOnItemClickListener(final OnItemClickListener linkedListener) {
this.linkedListener = linkedListener;
}
}
Where can I put check for visibility in this Adapter?
This works but will be overwritten by the getView() method in the adapter . You must handle this in the adapter bcoz each time view becomes visible on the screen the View is updated so becomes visible in your case.
For the Data you are storing add a Visibility field ( by default keep it visible ) and change the Visibility to GONE in the onClick() method.
if you dont understand , post me your code and will let you know what changes to make.

Categories

Resources