RecycleView repeat action on one recycleview card on other - android

I am developing one quiz android application in which questions and their respective options and answer will be fetched from server and added to recycle view.
I have done coding of same and it is working except one problem that when i choose any option i turn its background green if it is right or i turn it to red if it is wrong but when i do same for any question same action is been transformed on other questions option in recycle view.
As i click on Option A
6th question from previous solved question have option A automatically selected
I am posting my Adapter and Fragment code for same.
Adapter code:-
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(context);
Log.e("I : ", "Creating " );
switch (viewType) {
case QUESTION:
View viewQuestion = inflater.inflate(R.layout.question_card, parent, false);
viewHolder = new QuestionFeed(viewQuestion);
break;
case LOADING:
View viewLoading = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(viewLoading);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final PostRead result = postResults.get(position);
String catname = null;
try {
catname = dataBaseHelper.getCatName(result.getCat());
} catch (SQLException e) {
e.printStackTrace();
}
Log.e("Position: ", "" + position);
switch (getItemViewType(position)) {
case QUESTION:
final QuestionFeed textFeed = (QuestionFeed) holder;
textFeed.question.setText(result.getQuestion());
textFeed.optionA.setText(result.getA());
textFeed.optionB.setText(result.getB());
textFeed.optionC.setText(result.getC());
textFeed.optionD.setText(result.getD());
textFeed.answerView.setText(catname);
textFeed.time.setText("" + TimeAgo.getTimeAgo((10000000000000L - result.getTimestamp())));
textFeed.optionA_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (result.getAnswer().equals("a")) {
Log.e("AAAAnswer- ", result.getAnswer());
textFeed.optionA_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else {
Log.e("Answer- ", result.getAnswer());
textFeed.optionA_layout.setBackgroundColor(context.getResources().getColor(R.color.wrong_answer));
if (result.getAnswer().equals("b")) {
textFeed.optionB_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("c")) {
textFeed.optionC_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("d")) {
textFeed.optionD_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
}
}
if (textFeed.descView.getVisibility() == View.GONE) {
textFeed.descView.setVisibility(View.VISIBLE);
}
}
});
textFeed.optionB_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (result.getAnswer().equals("b")) {
Log.e("BBBAnswer- ", result.getAnswer());
textFeed.optionB_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else {
textFeed.optionB_layout.setBackgroundColor(context.getResources().getColor(R.color.wrong_answer));
if (result.getAnswer().equals("a")) {
textFeed.optionA_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("c")) {
textFeed.optionC_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("d")) {
textFeed.optionD_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
}
}
if (textFeed.descView.getVisibility() == View.GONE) {
textFeed.descView.setVisibility(View.VISIBLE);
}
}
});
textFeed.optionC_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (result.getAnswer().equals("c")) {
Log.e("CCCAnswer- ", result.getAnswer());
textFeed.optionC_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else {
textFeed.optionC_layout.setBackgroundColor(context.getResources().getColor(R.color.wrong_answer));
if (result.getAnswer().equals("b")) {
textFeed.optionB_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("a")) {
textFeed.optionA_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("d")) {
textFeed.optionD_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
}
}
if (textFeed.descView.getVisibility() == View.GONE) {
textFeed.descView.setVisibility(View.VISIBLE);
}
}
});
textFeed.optionD_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (result.getAnswer().equalsIgnoreCase("d")) {
Log.e("DDDAnswer- ", result.getAnswer());
textFeed.optionD_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else {
Log.e("DDDAnswer- ", result.getAnswer());
textFeed.optionD_layout.setBackgroundColor(context.getResources().getColor(R.color.wrong_answer));
if (result.getAnswer().equals("b")) {
textFeed.optionB_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("c")) {
textFeed.optionC_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
} else if (result.getAnswer().equals("a")) {
textFeed.optionA_layout.setBackgroundColor(context.getResources().getColor(R.color.right_answer));
}
}
if (textFeed.descView.getVisibility() == View.GONE) {
textFeed.descView.setVisibility(View.VISIBLE);
}
}
});
break;
}
}
#Override
public int getItemCount() {
return postResults == null ? 0 : postResults.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return QUESTION;
}
public void add(PostRead r) {
postResults.add(r);
notifyItemInserted(postResults.size() - 1);
}
public void addAll(List<PostRead> moveResults) {
for (PostRead result : moveResults) {
add(result);
}
notifyDataSetChanged();
}
public void remove(PostRead r) {
int position = postResults.indexOf(r);
if (position > -1) {
postResults.remove(position);
notifyItemRemoved(position);
}
}
public void clear() {
isLoadingAdded = false;
while (getItemCount() > 0) {
remove(getItem(0));
}
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addLoadingFooter() {
isLoadingAdded = true;
add(new PostRead());
}
public void removeLoadingFooter() {
isLoadingAdded = false;
int position = postResults.size() - 1;
PostRead result = getItem(position);
if (result != null) {
postResults.remove(position);
notifyItemRemoved(position);
}
}
public PostRead getItem(int position) {
return postResults.get(position);
}
protected class QuestionFeed extends RecyclerView.ViewHolder {
private ImageView back, share;
private MyTextView question;
private MyTextView optionA, optionB, optionC, optionD, answerView, time;
private LinearLayout optionA_layout, optionB_layout, optionC_layout, optionD_layout, errorLayout, descView;
private ProgressBar mProgress;
private Button btnRetry;
private TextView txtError;
private RelativeLayout mainLayout, backButton;
public QuestionFeed(View itemView) {
super(itemView);
back = (ImageView) itemView.findViewById(R.id.backView);
back = (ImageView) itemView.findViewById(R.id.share);
question = (MyTextView) itemView.findViewById(R.id.question);
optionA = (MyTextView) itemView.findViewById(R.id.optionA);
optionB = (MyTextView) itemView.findViewById(R.id.optionB);
optionC = (MyTextView) itemView.findViewById(R.id.optionC);
optionD = (MyTextView) itemView.findViewById(R.id.optionD);
answerView = (MyTextView) itemView.findViewById(R.id.subject);
time = (MyTextView) itemView.findViewById(R.id.time);
optionA_layout = (LinearLayout) itemView.findViewById(R.id.optionbuttonA);
optionB_layout = (LinearLayout) itemView.findViewById(R.id.optionbuttonB);
optionC_layout = (LinearLayout) itemView.findViewById(R.id.optionbuttonC);
optionD_layout = (LinearLayout) itemView.findViewById(R.id.optionbuttonD);
mProgress = (ProgressBar) itemView.findViewById(R.id.main_progress);
mainLayout = (RelativeLayout) itemView.findViewById(R.id.content_sign_up);
backButton = (RelativeLayout) itemView.findViewById(R.id.back_button);
descView = (LinearLayout) itemView.findViewById(R.id.desc);
errorLayout = (LinearLayout) itemView.findViewById(R.id.error_layout);
btnRetry = (Button) itemView.findViewById(R.id.error_btn_retry);
txtError = (TextView) itemView.findViewById(R.id.error_txt_cause);
}
}
Fragment Code
private void loadFirstPage() {
hideErrorView();
Query query = postRef.orderByChild("timestamp").startAt(firstTime).limitToFirst(14);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<PostRead> allPosts = new ArrayList<>();
childCount = (int) dataSnapshot.getChildrenCount();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
// TODO: handle the post
Log.e("Online ", "" + firstTime);
PostRead catItems = postSnapshot.getValue(PostRead.class);
catItems.setPostkey(postSnapshot.getKey());
allPosts.add(catItems);
childCount--;
if (childCount == 0) {
firstStart = 0;
dataBaseHelper.updatePosts(allPosts);
hideErrorView();
progressBar.setVisibility(View.GONE);
adapter.addAll(allPosts);
isLoading = false;
if (allPosts.size() == 0) {
isLastPage = true;
} else adapter.addLoadingFooter();
}
firstTime = catItems.getTimestamp();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

That is because Views are recycled by RecyclerView and you are setting background color to different color manually.
The solution is to set default color for background of your textFeed in BindViewHolder as:
textFeed.optionA_layout.setBackgroundColor(context.getResources().getColor(R.color.default_color));
textFeed.optionB_layout.setBackgroundColor(context.getResources().getColor(R.color.default_color));
textFeed.optionC_layout.setBackgroundColor(context.getResources().getColor(R.color.default_color));
textFeed.optionD_layout.setBackgroundColor(context.getResources().getColor(R.color.default_color));

Related

How to Avoid ANR while loading 100+ object from server and setting It to adapter ; in android [duplicate]

This question already has an answer here:
how to fix Application not responding?
(1 answer)
Closed 4 years ago.
I have MainActivity which calls server using AsyncTask and gets 100+ list of objects from server after getting I'm using adapter to set these list in listview. This time if I perform any action app shows ANR after some times app will work normally if I Open that page again and do the same operation same problem occurs.
Note : I'm using AsyncTask to get objects from server.
Setting listView adapter taking more time how to do this in background.
Please give some suggestions to avoid this.
Adapter Code :
public abstract class MatchedRegularUsersAdapter extends BaseAdapter
{
private final static String LOG_TAG = MatchedRegularUsersAdapter.class.getName();
private LayoutInflater inflater = null;
protected final List<MatchedRegularUser> availableMatches;
protected Ride ride;
protected final AppCompatActivity activity;
private boolean isConnectedMatch=false;
private Drawable defaultFeMale,defaultMale;
private List<MatchedRegularUser> matchedRegularUser = new ArrayList<>();
private Map<Integer,UserHolder> userHolderMap = new HashMap<>();
protected LongSparseArray<MatchedUserCachedDetails> cachedDetailsMap = new LongSparseArray<>();
protected MatchedUsersDisplayActivity MatchedRegularUsersDisplayActivity ;
protected MatchedRegularUsersAdapter(AppCompatActivity activity, List<MatchedRegularUser> availableMatches,Ride ride,boolean isConnectedMatch)
{
super();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.availableMatches = availableMatches;
this.ride = ride;
this.activity = activity;
this.isConnectedMatch = isConnectedMatch;
}
#Override
public int getCount()
{
return availableMatches.size();
}
#Override
public MatchedRegularUser getItem(int index)
{
return availableMatches.get(index);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
final UserHolder userHolder;
try
{
if (view == null) {
view = inflater.inflate(R.layout.row_regular_user_new, parent, false);
userHolder = new UserHolder();
userHolder.startLocation = (TextView) view.findViewById(R.id.regular_start_location_user);
userHolder.endLocation = (TextView) view.findViewById(R.id.regular_end_location_user);
userHolder.time = (TextView) view.findViewById(R.id.timeResults);
userHolder.points = (TextView) view.findViewById(R.id.actual_fare);
userHolder.pointsTv = (TextView)view.findViewById(R.id.points_textview);
userHolder.pointsLayout = (LinearLayout)view.findViewById(R.id.points_layout);
userHolder.userImage = (ImageView) view.findViewById(R.id.regular_userImageResults);
userHolder.userName = (TextView) view.findViewById(R.id.regular_usernameResults);
userHolder.pickUpTimeLayout = (LinearLayout)view.findViewById(R.id.user_trip_time_layout);
userHolder.verificationStatusImageView = (ImageView) view.findViewById(R.id.verification_status_imageView);
userHolder.companyNameTextView = (TextView) view.findViewById(R.id.companyNameTextView);
userHolder.ratingLinearLayout = (LinearLayout) view.findViewById(R.id.ratingLinearLayout);
userHolder.userRating = (ImageView) view.findViewById(R.id.regular_userratingResults);
userHolder.noOfReviewsTv = (TextView) view.findViewById(R.id.noOfReviewsTv);
userHolder.amOrPM = (TextView) view.findViewById(R.id.timeAMorPM);
userHolder.vehicleModelIcon = (ImageView) view.findViewById(R.id.matched_user_vehicle_model_icon);
userHolder.rideStatusTextView = (TextView) view.findViewById(R.id.rideStatusTV);
userHolder.matchedPerTextView = (TextView) view.findViewById(R.id.matchingPerTextView);
userHolder.percentageLayout = (LinearLayout) view.findViewById(R.id.percentageLayout);
userHolder.lastRideCreatedTimeTextView = (TextView)view.findViewById(R.id.lastRideCreatedTime);
userHolder.noOfSeatsAndInvitedLayout = (LinearLayout) view.findViewById(R.id.noOfSeatsAndInvitedLayout);
userHolder.noOfSeatsTextView = (TextView) view.findViewById(R.id.noOfSeatsTextView);
userHolder.seatsTextView = (TextView) view.findViewById(R.id.seats_textview);
userHolder.longDistanceDateTv=(TextView)view.findViewById(R.id.long_distance_date);
userHolder.callOptionLayout=(LinearLayout)view.findViewById(R.id.call_image_layout);
userHolder.callImageLayout=(ImageView) view.findViewById(R.id.call_image);
userHolder.favouriteUserIcon = (ImageView)view.findViewById(R.id.fav_user_icon);
userHolder.verifiedStatus = (LinearLayout) view.findViewById(R.id.verification_layout);
userHolder.startDate = (LinearLayout) view.findViewById(R.id.startDate);
userHolder.endDate = (LinearLayout) view.findViewById(R.id.endtDate);
userHolder.fromDate = (TextView) view.findViewById(R.id.regular_matched_fromDate);
userHolder.toDate = (TextView) view.findViewById(R.id.regular_matched_toDate);
userHolder.toDateLabel = (TextView) view.findViewById(R.id.regular_matched_toDate_label);
userHolder.weekdaysLytLayout = (HorizontalScrollView) view.findViewById(R.id.regular_week_days_layout);
userHolder.weekdaysLyt = (LinearLayout) view.findViewById(R.id.regular_week_day_view);
userHolder.sendInviteLyt = (LinearLayout) view.findViewById(R.id.regular_send_invite_lyt);
userHolder.actionLabel = (TextView) view.findViewById(R.id.regular_send_invite_text);
userHolder.moreDetail = (LinearLayout) view.findViewById(R.id.moreDetailsLayout);
userHolder.moreDetailsTv = (TextView) view.findViewById(R.id.more_details);
userHolder.moreDetailImage = (ImageView) view.findViewById(R.id.arrow_down_image);
userHolder.wholeWeekdaysLayout = (LinearLayout) view.findViewById(R.id.weekdaysLayout);
userHolder.rideNote = (LinearLayout)view.findViewById(R.id.ride_note_layout);
view.setTag(userHolder);
} else {
userHolder = (UserHolder) view.getTag();
}
final MatchedRegularUser userInfo = availableMatches.get(position);
userHolder.startLocation.setText(LocationClientUtils.getConsolidatedNameFromFormattedAddressForLocationAlert(userInfo.getFromLocationAddress()));
userHolder.endLocation.setText(LocationClientUtils.getConsolidatedNameFromFormattedAddressForLocationAlert(userInfo.getToLocationAddress()));
userHolder.userImage.setId(position);
userHolder.userName.setText(userInfo.getName());
setRatingAndNoOfReviews(userHolder, userInfo);
setRideTime(userHolder, userInfo);
setVerificationStatusDetails(userHolder, userInfo,view);
setUsersImage(userHolder, userInfo);
setVehicleDetails(userHolder, userInfo);
setPointsTextViewAndColors(userHolder,userInfo,position,view);
setNoOfSeatsOrOnTime(userHolder,userInfo);
setFavouriteUserIndication(userHolder,userInfo);
setRideNote(userHolder,userInfo);
setActionLayout(userHolder.actionLabel);
userHolder.sendInviteLyt.setId(position);
userHolder.sendInviteLyt.setOnClickListener(inviteOnClickListener);
setBackgroundAndLastRideCreatedTimeIfRequired(view, userHolder, userInfo);
setMatchedPercentageText(userHolder, userInfo);
setWeekDays(userHolder.weekdaysLyt, userInfo);
userHolder.fromDate.setText(DateUtils.getDateWithOutSpecialChars(userInfo.getMatchedFromDate()));
if (userInfo.getMatchedToDate() == null) {
userHolder.endDate.setVisibility(View.GONE);
userHolder.toDate.setVisibility(View.GONE);
} else {
userHolder.toDate.setText(DateUtils.getDateWithOutSpecialChars(userInfo.getMatchedToDate()));
}
if(isConnectedMatch)
{
userHolder.moreDetail.setVisibility(View.GONE);
userHolder.wholeWeekdaysLayout.setVisibility(View.VISIBLE);
}
userHolder.moreDetail.setId(position);
userHolder.moreDetail.setTag(position);
userHolder.moreDetail.setOnClickListener(moreOnClickListener);
userHolderMap.put(position,userHolder);
checkForSelectedUser(userInfo,userHolder);
}
catch (Throwable th)
{
Log.e(LOG_TAG,"getView() failed",th);
}
return view;
}
private final View.OnClickListener moreOnClickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try {
UserHolder userHolder = userHolderMap.get(v.getId());
MatchedRegularUser matchedRegularuser = availableMatches.get(v.getId());
if(!matchedRegularUser.contains(matchedRegularuser))
{
userHolder.moreDetailImage.setImageDrawable(activity.getResources().getDrawable(R.drawable.dropdown_close_3x));
userHolder.moreDetailsTv.setText("Less");
userHolder.wholeWeekdaysLayout.setVisibility(View.VISIBLE);
matchedRegularUser.add(matchedRegularuser);
refreshAdapter();
}
else
{
userHolder.wholeWeekdaysLayout.setVisibility(View.GONE);
userHolder.moreDetailsTv.setText("More");
userHolder.moreDetailImage.setImageDrawable(activity.getResources().getDrawable(R.drawable.dropdown_3x));
matchedRegularUser.remove(matchedRegularuser);
refreshAdapter();
}
}catch (Throwable th)
{
Log.i(LOG_TAG, "inside moreOnclickListener");
}
}
};
private void setMatchedPercentageText(UserHolder userHolder, MatchedRegularUser userInfo)
{
if(isConnectedMatch)
{
userHolder.percentageLayout.setVisibility(View.GONE);
}
else {
userHolder.matchedPerTextView.setVisibility(View.VISIBLE);
if ((MatchedRegularUser.REGULAR_PASSENGER.equalsIgnoreCase(userInfo.getUserRole())) && userInfo.getMatchPercentageOnMatchingUserRoute() != 0) {
userHolder.matchedPerTextView.setText(userInfo.getMatchPercentage() + "%" + " (" + userInfo.getMatchPercentageOnMatchingUserRoute() + "%)");
} else {
userHolder.matchedPerTextView.setText(userInfo.getMatchPercentage() + "%");
}
}
}
private void setNoOfSeatsOrOnTime(UserHolder userHolder, MatchedUser userInfo)
{
if(userInfo instanceof MatchedRegularUser)
{
if(((MatchedRegularUser)userInfo).getUserOnTimeComplianceRating()==null){
userHolder.noOfSeatsAndInvitedLayout.setVisibility(View.INVISIBLE);
}else {
userHolder.noOfSeatsTextView.setText(((MatchedRegularUser)userInfo).getUserOnTimeComplianceRating()+"%");
userHolder.noOfSeatsTextView.setSingleLine();
userHolder.seatsTextView.setText("On Time");
// userHolder.seatTextview.setTextColor(activity.getResources().getColor(R.color.fav_footer_bg_one));
}
}
if(isConnectedMatch){
userHolder.noOfSeatsAndInvitedLayout.setVisibility(View.GONE);
}
}
private void setPointsTextViewAndColors(final UserHolder userHolder, MatchedRegularUser userInfo, int position, View view)
{
if(isConnectedMatch)
{
userHolder.pointsLayout.setVisibility(View.GONE);
}
else {
userHolder.points.setVisibility(View.VISIBLE);
double pointsToShow = userInfo.getPoints();
userHolder.points.setText(String.valueOf(StringUtil.getPointsWithTwoDecimal(pointsToShow)));
}
}
public void navigateToProfile(MatchedRegularUser MatchedRegularUser) {
boolean isContactOptionRequired =true;
if (!RideViewUtils.getUserQualifiedToDisplayContact()) {
isContactOptionRequired = false;
}
Intent viewIntent = new Intent(activity, ActivityUtils.getProfileDisplayClass(QuickRideApplication.getApplicationName(QuickRideApplication.getInstance().getApplicationContext())));
viewIntent.putExtra(ProfileDisplayActivity.USER_ID, String.valueOf( MatchedRegularUser.getUserid()));
viewIntent.putExtra(ProfileDisplayActivity.IS_JOIN_ACTION_REQUIRED, false);
viewIntent.putExtra(ProfileDisplayActivity.IS_CONTACT_LAYOUT_REQUIRED, isContactOptionRequired);
MatchedRegularUsersDisplayActivity.startActivity(viewIntent);
}
private void setImageAndTextColorsBasedOnMatchedRegularUser(UserHolder userHolder,MatchedRegularUser userInfo)
{
if(userInfo.getRideid()==0)
{
userHolder.userImage.setAlpha((float)0.5);
userHolder.userName.setTextColor(activity.getResources().getColor(R.color._9B9B9B));
userHolder.startLocation.setTextColor(activity.getResources().getColor(R.color._9B9B9B));
userHolder.endLocation.setTextColor(activity.getResources().getColor(R.color._9B9B9B));
}
else
{
userHolder.userImage.setAlpha((float)1);
userHolder.userName.setTextColor(activity.getResources().getColor(R.color._5050550));
userHolder.startLocation.setTextColor(activity.getResources().getColor(R.color._363636));
userHolder.endLocation.setTextColor(activity.getResources().getColor(R.color._363636));
}
}
private void setBackgroundAndLastRideCreatedTimeIfRequired(View view,UserHolder userHolder,MatchedRegularUser userInfo)
{
if(userInfo.getRideid()==0)
{
view.setBackground(activity.getResources().getDrawable(R.drawable.listview_grey_selector));
userHolder.lastRideCreatedTimeTextView.setVisibility(View.VISIBLE);
userHolder.lastRideCreatedTimeTextView.setText(getTextForLastRideCreated(userInfo.getLastRideCreatedTime()));
}
else
{
view.setBackground(activity.getResources().getDrawable(R.drawable.listview_selector));
userHolder.lastRideCreatedTimeTextView.setVisibility(View.GONE);
userHolder.lastRideCreatedTimeTextView.setText(null);
}
}
private String getTextForLastRideCreated(Date lastRideCreatedTime)
{
Date currentDate = new Date();
int dateDifference = 1;
if(lastRideCreatedTime !=null && lastRideCreatedTime.getTime() < currentDate.getTime())
{
dateDifference = DateUtils.calculateTimeDifferenceBetweenDatesInDays(currentDate,lastRideCreatedTime);
if(dateDifference <1)
{
dateDifference = 1;
}
}
String text = activity.getResources().getString(R.string.last_ride_created);
if(dateDifference ==1)
{
text = text+dateDifference+activity.getResources().getString(R.string.day_ago);
}
else
{
text = text+dateDifference+activity.getResources().getString(R.string.days_ago);
}
return text;
}
private void setActionLayout( TextView actionLabel)
{
if(isConnectedMatch)
{
actionLabel.setText(activity.getString(R.string.remove));
}
else
{
actionLabel.setText(activity.getString(R.string.send_invite));
}
}
private void setUsersImage(final UserHolder userHolder, MatchedRegularUser userInfo)
{
Log.i(LOG_TAG, "setting of users image");
if(userInfo == null)
{
if(activity != null && !activity.isFinishing())Toast.makeText(activity,activity.getResources().getString(R.string.unableToProcess),Toast.LENGTH_SHORT).show();
return;
}
ImageCache imageCache = ImageCache.getInstance();
if(imageCache == null || userInfo.getImageURI()==null)
{
getDefaultUserImageForGuest(userHolder.userImage,userInfo);
}
else
{getDefaultUserImageForGuest(userHolder.userImage, userInfo);
if(userInfo.getImageURI() != null && !userInfo.getImageURI().isEmpty())
{
imageCache.getUserImage(userInfo.getImageURI(), userInfo.getGender(), ImageCache.SSIZE, userHolder.userImage, null,String.valueOf(userInfo.getUserid()),false);
}
}
}
private void getDefaultUserImageForGuest(ImageView userImageView, MatchedRegularUser userInfo)
{..
}
private final View.OnClickListener inviteOnClickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
final MatchedRegularUser matchedRegularUser= availableMatches.get(v.getId());
if(matchedRegularUser == null) return;
if(isConnectedMatch)
{
QuickRideModalDialog.displayConfirmationsDialog(activity, activity.getResources().getString(R.string.confirm_cancel_title), new QuickRideModalDialog.ModelDialogActionListener() {
#Override
public void doPrimaryAction() {
onRemoveClick(matchedRegularUser);
}
#Override
public void doSecondaryAction() {
}
});
}
else
{
onInviteClick(matchedRegularUser);
}
}
};
private void setFavouriteUserIndication(UserHolder userHolder, MatchedRegularUser MatchedRegularUser)
{
if(UserDataCache.getCacheInstance().isFavouritePartner(MatchedRegularUser.getUserid()))
{
userHolder.favouriteUserIcon.setVisibility(View.VISIBLE);
}else {
userHolder.favouriteUserIcon.setVisibility(View.GONE);
}
}
private void setVerificationStatusDetails(UserHolder userHolder, MatchedRegularUser userInfo, View view)
{
}
private void setRideTime(final UserHolder userHolder, final MatchedRegularUser userInfo)
{ if(isConnectedMatch)
{
userHolder.pickUpTimeLayout.setVisibility(View.GONE);
}
else if(userInfo instanceof MatchedRegularPassenger && userInfo.getPassengerReachTimeToPickup() != null){
userHolder.time.setText(DateUtils.getTimeStringFromDateForSingleDigitForHours(
userInfo.getPassengerReachTimeToPickup()));
userHolder.amOrPM.setText(DateUtils.getTimeStringFromDateOnlyMeridian(userInfo.getPassengerReachTimeToPickup()));
}else{
userHolder.time.setText(DateUtils.getTimeStringFromDateForSingleDigitForHours(
userInfo.getPickupTime()));
userHolder.amOrPM.setText(DateUtils.getTimeStringFromDateOnlyMeridian(
userInfo.getPickupTime()));
}
LinearLayout.LayoutParams pickUpLayout = (LinearLayout.LayoutParams) userHolder.pickUpTimeLayout.getLayoutParams();
LinearLayout.LayoutParams rateLayout = (LinearLayout.LayoutParams) userHolder.ratingLinearLayout.getLayoutParams();
}
private void setRatingAndNoOfReviews(UserHolder userHolder, MatchedRegularUser userInfo)
{
}
private void setVehicleDetails(UserHolder userHolder, MatchedRegularUser userInfo)
{
if(userInfo instanceof MatchedRegularRider)
{
}
else
{
userHolder.vehicleModelIcon.setVisibility(View.INVISIBLE);
}
}
protected abstract void onInviteClick(MatchedRegularUser matchedRegularUser);
protected abstract void onRemoveClick(MatchedRegularUser matchedRegularUser);
protected abstract void completeInvite(MatchedRegularUser matchedRegularUser);
private void setWeekDays(LinearLayout weekDays,MatchedRegularUser MatchedRegularUser)
{
....
}
private void checkForSelectedUser(MatchedRegularUser matchedRegularuser, UserHolder userHolder)
{
if(isConnectedMatch)
{
userHolder.moreDetail.setVisibility(View.GONE);
userHolder.wholeWeekdaysLayout.setVisibility(View.VISIBLE);
}
}
private void refreshAdapter()
{
if(activity !=null && activity instanceof CommonMapActivity)
{
CommonMapActivity commonMapActivity = (CommonMapActivity)activity;
..
}
}
private boolean checkForMoreDetailsClicked(MatchedRegularUser matchedRegularuser,List<MatchedRegularUser> matchedRegularUser) {
..
return isMatchedUserPresent;
}
private void addWeekDayView(Time timeOfDay,String nameOfDay,LinearLayout weekDays)
{
......
}
static class UserHolder
{
ImageView userImage,moreDetailImage,favouriteUserIcon,userRating,verificationStatusImageView,vehicleModelIcon,callImageLayout;
TextView userName, startLocation, endLocation,fromDate,toDate,actionLabel,toDateLabel,noOfReviewsTv,companyNameTextView,amOrPM,time,noOfSeatsTextView,seatsTextView;
LinearLayout rideNote,wholeWeekdaysLayout,weekdaysLyt,startDate,endDate,sendInviteLyt,verifiedStatus,moreDetail,ratingLinearLayout,pickUpTimeLayout,percentageLayout,noOfSeatsAndInvitedLayout,pointsLayout,callOptionLayout;
HorizontalScrollView weekdaysLytLayout;
TextView longDistanceDateTv,moreDetailsTv,lastRideCreatedTimeTextView,points,pointsTv,rideStatusTextView,matchedPerTextView,sendInviteTextView;
}
}
MainActivity.java
...
matchinglist.setOnclickListener(new onClickListener)
{
setAdapter();
...
}
Well the problem is - your application trying to handle all those items at once.
First of all use recyclerView instead of listview,
RecyclerView vs. ListView
2nd try to add pagination to your application https://developer.android.com/topic/libraries/architecture/paging/

While searching using EditText, the items in Recyclerview is duplicating, if i am searching fast

In my project, there is need of searching data from server using keyword. After search, i am displaying results using RecyclerView . While searching fast, the data in RecyclerView is duplicating. If searching slowly, it's working fine. Any suggestions are appreciated. Thank you.
The below code for making server call:
private void callSearchUserApi(final String searchText, int currentPage, boolean clearData) {
isApiCallInProcess = true;
String URL = "userinfo/api/v1/user-search/" + "?page=" + currentPage;
if (!Connectivity.isConnected(activity)) {
Common.snackBarNoConnection(activity, activity.getString(R.string.no_conection));
//setOnProgressbarVisibility(View.GONE);
return;
}
if (clearData) {
globalSearchUsersModelList.clear();
//BS globalSearchUserResultsAdapter.notifyDataSetChanged();
}
ApiInterface apiCall = ApiClient.getApiService(activity);
final Call<SearchUsersModel> globalUserSearchApiCall = apiCall.searchUser(
URL,
searchText);
globalUserSearchApiCall.enqueue(new Callback<SearchUsersModel>() {
#Override
public void onResponse(Call<SearchUsersModel> call, Response<SearchUsersModel> response) {
if (response.isSuccessful() && response.body().getStatus().equalsIgnoreCase(Common.SUCCESS_RESPONSE)) {
//BS globalSearchUsersModelList.addAll(response.body().getData().getData());
for (int i = 0; i < response.body().getData().getData().size(); i++) {
SearchUsersModel.DataBeanX.DataBean dataBean = new SearchUsersModel.DataBeanX.DataBean();
dataBean.setDesignation(response.body().getData().getData().get(i).getDesignation());
dataBean.setFull_name(response.body().getData().getData().get(i).getFull_name());
dataBean.setGender(response.body().getData().getData().get(i).getGender());
dataBean.setId(response.body().getData().getData().get(i).getId());
dataBean.setPlace(response.body().getData().getData().get(i).getPlace());
dataBean.setProfile_pic(response.body().getData().getData().get(i).getProfile_pic());
globalSearchUsersModelList.add(dataBean);
/*BS if (!globalSearchUsersModelList.contains(response.body().getData().getData().get(i)))
globalSearchUsersModelList.add(response.body().getData().getData().get(i));*/
}
CURRENT_PAGE = response.body().getData().getPage();
isLoading = false;
if (response.body().getData().isNext() == false)
isLastPage = true;
else
isLastPage = false;
if (globalSearchUsersModelList.size() == 0) {
rv_GlobalsearchList.setVisibility(View.GONE);
rl_placeholderGSPeople.setVisibility(View.VISIBLE);
tv_placeholderGSPeople.setText(activity.getString(R.string.no_search_found) + " " + searchText);
} else {
rv_GlobalsearchList.setVisibility(View.VISIBLE);
rl_placeholderGSPeople.setVisibility(View.GONE);
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
globalSearchUserResultsAdapter.notifyDataSetChanged();
}
});
}
if (searchTextsList.size() > 0) {
String sText = searchTextsList.get(0);
searchTextsList.remove(0);
callSearchUserApi(sText, FIRST_PAGE, true);
} else
isApiCallInProcess = false;
}
#Override
public void onFailure(Call<SearchUsersModel> call, Throwable t) {
isApiCallInProcess = false;
}
});
}
This is my Adapter.
public class GlobalSearchUserResultsAdapter extends RecyclerView.Adapter<GlobalSearchUserResultsAdapter.SearchViewHolder> {
private Context context;
private List<SearchUsersModel.DataBeanX.DataBean> searchUserList;
public GlobalSearchUserResultsAdapter(Context context, List<SearchUsersModel.DataBeanX.DataBean> searchUserList){
this.context = context;
this.searchUserList = searchUserList;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.v("Search", "Adapter Activity : "+context);
View view = LayoutInflater.from(context).inflate(R.layout.global_search_row, parent, false);
return new GlobalSearchUserResultsAdapter.SearchViewHolder(view);
}
#Override
public void onBindViewHolder(GlobalSearchUserResultsAdapter.SearchViewHolder holder, int position) {
if ( searchUserList.get(position).getGender().equals("M")) {
holder.iv_userImage.setBackgroundResource(R.drawable.white_border_with_circle_appblue);
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
/*searchUsersModel*/searchUserList.get(position).getProfile_pic(),
R.drawable.male,
true);
} else if (searchUserList.get(position).getGender().equals("F")) {
holder.iv_userImage.setBackgroundResource(R.drawable.white_border_with_circle_pink);
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
searchUserList.get(position).getProfile_pic(),
R.drawable.female,
true);
} else {
Common.setGlideImage((GlobalSearchActivity)context,
holder.iv_userImage,
searchUserList.get(position).getProfile_pic(),
R.drawable.deafult_profilepic,
true);
}
holder.tv_userName.setText(searchUserList.get(position).getFull_name());
holder.tv_userName.setTypeface(Common
.getFontTypeface(context, GlobalConstants.FONT_AVENIR_MEDIUM));
holder.tv_place.setText(searchUserList.get(position).getPlace());
holder.tv_place.setTypeface(Common
.getFontTypeface(context, GlobalConstants.FONT_AVENIR_MEDIUM));
holder.designation.setText(searchUserList.get(position).getDesignation());
}
#Override
public int getItemCount() {
return searchUserList.size();
}
public class SearchViewHolder extends RecyclerView.ViewHolder{
private ImageView iv_userImage;
private TextView tv_userName;
private TextView tv_place;
private TextView designation;
public SearchViewHolder(View itemView) {
super(itemView);
this.iv_userImage = (ImageView) itemView.findViewById(R.id.imageSearch);
this.tv_userName = (TextView) itemView.findViewById(R.id.nameSearch);
tv_userName.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_MEDIUM));
this.designation = (TextView) itemView.findViewById(R.id.designation);
designation.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_MEDIUM));
this.tv_place = (TextView) itemView.findViewById(R.id.placeSearch);
tv_place.setTypeface(Common.getFontTypeface(context,
GlobalConstants.FONT_AVENIR_LIGHT));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, ProfileActivity.class)//ThirdParty
.putExtra(GlobalConstants.KEY_THIRD_PARTY_ID, searchUserList.get(getAdapterPosition()).getId()));
}
});
}
}
}
You just had to clear the globalSearchUsersModelList list just before for loop, because API call is asynchronous.
globalSearchUsersModelList.clear();// Important one
for (int i = 0; i < response.body().getData().getData().size(); i++) {
// do your stuff
}
I think the issue come from your getItemId implementation. The way you implement it, the recycler view will identify an item according to its position in the list.
If you change this and use unique identification for instance searchUserList.get(position).id (if your User object has an unique ID) the problem should be fixed
You can also add in your activity adapter.setHasStableIds(true)

callback in recyclerview affect all cells

I have a button in every cell of a RecyclerView that launches a download network call. The cell displays differently according to whether it's downloading, downloaded or finished.
my simplified code :
#Override public void onBindViewHolder(final CatalogViewHolder holder, int position) {
final DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
#Override public void started() {
mainThreadHandler.post(new Runnable() {
#Override public void run() {
holder.itemView.setBackground(//color1
}
});
}
#Override public void finished() {
mainThreadHandler.post(new Runnable() {
#Override public void run() {
holder.itemView.setBackground(//color 2
}
});
}
#Override public void error(Exception e) {
mainThreadHandler.post(new Runnable() {
#Override public void run() {
holder.itemView.setBackground(//color 3
}
});
}
};
holder.button1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
assyncCall(statusCallback);
}
});
}
The first time i clic on a cell, everything works fine. If I clic on the download button of another cell, both of them will update.
I understand that's due to recyclerview recycling cells, but I can't figure out how to do better.
Thanks !
my full adapter :
public class CatalogRecyclerAdapter extends RecyclerView.Adapter<CatalogViewHolder> {
public static final String TAG = "CatalogRecyclerAdapter";
private final LayoutInflater inflater;
private final DownloadCenter downloadCenter;
private final ListInterface.FlowController flowController;
private final ResourcesStringRepository resourcesStringRepository;
private final ImageManagerFactory imageManagerFactory;
private final Handler mainThreadHandler;
public CatalogRecyclerAdapter(LayoutInflater inflater, ListInterface.FlowController flowController,
DownloadCenter downloadCenter, ResourcesStringRepository resourcesStringRepository,
ImageManagerFactory imageManagerFactory, Handler mainThreadHandler) {
this.inflater = inflater;
this.flowController = flowController;
this.downloadCenter = downloadCenter;
this.resourcesStringRepository = resourcesStringRepository;
this.imageManagerFactory = imageManagerFactory;
this.mainThreadHandler = mainThreadHandler;
}
private static final int TITLE = 0;
private static final int USER = 2;
private static final int PROGRAM = 3;
private static final int COURSE = 4;
private static final int GROUP = 5;
private static final int MEDIA = 6;
private static final int ERROR = 7;
private static final int DEMO = 8;
//The list of all elements
private List<FilterableUser> users = new ArrayList<>();
private List<CatalogProgram> programs = new ArrayList<>();
private List<CatalogProgram> demos = new ArrayList<>();
private List<CatalogCourse> courses = new ArrayList<>();
private List<FilterableGroup> groups = new ArrayList<>();
private List<CatalogMedia> medias = new ArrayList<>();
//The list that will be displayed after filtering and research.
List<Object> displayedList = new ArrayList<>();
static final String TITLES[] = new String[10];
static {
Context ctx = M360Application.getContext();
TITLES[USER] = ctx.getString(R.string.users);
TITLES[PROGRAM] = ctx.getString(R.string.programs);
TITLES[COURSE] = ctx.getString(R.string.courses);
TITLES[GROUP] = ctx.getString(R.string.groups);
TITLES[MEDIA] = ctx.getString(R.string.documents);
TITLES[DEMO] = ctx.getString(R.string.programs_demo);
}
private String searchString;
#Override public int getItemViewType(int position) {
if (displayedList.get(position) instanceof String) {
return TITLE;
} else if (displayedList.get(position) instanceof FilterableUser) {
return USER;
} else if (displayedList.get(position) instanceof CatalogProgramDemo) {
return DEMO;
} else if (displayedList.get(position) instanceof CatalogProgram) {
return PROGRAM;
} else if (displayedList.get(position) instanceof CatalogCourse) {
return COURSE;
} else if (displayedList.get(position) instanceof FilterableGroup) {
return GROUP;
} else if (displayedList.get(position) instanceof CatalogMedia) {
return MEDIA;
} else if (displayedList.get(position) instanceof CatalogError) {
return ERROR;
} else {
throw new ClassCastException(
"this adapter's displayedList is corrupted" + displayedList.get(position).toString());
}
}
public void setData(List<Filterable> data, String searchedString) {
searchString = searchedString;
setData(data);
}
private void setData(List<Filterable> data) {
LogDev.i(TAG, "setting data size: " + data.size());
groups.clear();
users.clear();
programs.clear();
demos.clear();
courses.clear();
medias.clear();
for (Filterable element : data) {
if (element instanceof CatalogCourse) {
courses.add((CatalogCourse) element);
} else if (element instanceof FilterableUser) {
users.add((FilterableUser) element);
} else if (element instanceof CatalogProgramDemo) {
demos.add((CatalogProgramDemo) element);
} else if (element instanceof CatalogProgram) {
programs.add((CatalogProgram) element);
} else if (element instanceof FilterableGroup) {
groups.add((FilterableGroup) element);
} else if (element instanceof CatalogMedia) {
medias.add((CatalogMedia) element);
}
}
constructDataSet();
}
private void constructDataSet() {
displayedList.clear();
if (!demos.isEmpty()) {
displayedList.add(TITLES[DEMO]);
displayedList.addAll(demos);
}
if (!programs.isEmpty()) {
displayedList.add(TITLES[PROGRAM]);
displayedList.addAll(programs);
}
if (!courses.isEmpty()) {
displayedList.add(TITLES[COURSE]);
displayedList.addAll(courses);
}
if (!users.isEmpty()) {
displayedList.add(TITLES[USER]);
displayedList.addAll(users);
}
if (!groups.isEmpty()) {
displayedList.add(TITLES[GROUP]);
displayedList.addAll(groups);
}
if (!medias.isEmpty()) {
displayedList.add(TITLES[MEDIA]);
displayedList.addAll(medias);
}
if (displayedList.isEmpty()) {
displayedList.add(new CatalogError());
}
LogDev.w(TAG, "displayedList.size() : " + displayedList.size());
notifyDataSetChanged();
}
#Override public CatalogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TITLE:
return new TitleViewHolder(inflater.inflate(R.layout.item_list_title_catalog, parent, false));
case USER:
return new UserViewHolder(inflater.inflate(R.layout.widget_user_small, parent, false));
case PROGRAM:
case DEMO:
return new ProgramViewHolder(inflater.inflate(R.layout.widget_program_small, parent, false));
case COURSE:
return new CourseViewHolder(inflater.inflate(R.layout.widget_course_small, parent, false));
case GROUP:
return new GroupViewHolder(inflater.inflate(R.layout.widget_group_small, parent, false));
case MEDIA:
return new MediaViewHolder(inflater.inflate(R.layout.widget_media_small, parent, false));
case ERROR:
return new CatalogErrorViewHolder(inflater.inflate(R.layout.widget_noresult_small, parent, false));
default:
LogDev.e(TAG, "view type not supported");
return null;
}
}
#Override public void onBindViewHolder(CatalogViewHolder holder, int position) {
Object displayedObject = displayedList.get(position);
//holder.bind(displayedObject, errorDisplayInterface);
if (holder instanceof TitleViewHolder && displayedObject instanceof String) {
((TitleViewHolder) holder).tv.setText((String) displayedObject);
} else if (holder instanceof ProgramViewHolder && displayedObject instanceof CatalogProgram) {
bindProgramViewHolder((ProgramViewHolder) holder, (CatalogProgram) displayedObject);
} else if (holder instanceof CourseViewHolder && displayedObject instanceof CatalogCourse) {
bindCourseViewHolder((CourseViewHolder) holder, (CatalogCourse) displayedObject);
} else if (holder instanceof GroupViewHolder && displayedObject instanceof FilterableGroup) {
bindGroupViewHolder((GroupViewHolder) holder, (FilterableGroup) displayedObject);
} else if (holder instanceof UserViewHolder && displayedObject instanceof FilterableUser) {
bindUserViewHolder((UserViewHolder) holder, (FilterableUser) displayedObject);
} else if (holder instanceof MediaViewHolder && displayedObject instanceof CatalogMedia) {
bindMediaViewHolder((MediaViewHolder) holder, (CatalogMedia) displayedObject);
} else if (holder instanceof CatalogErrorViewHolder) {
//No binding with any data
} else {
throw new ClassCastException(displayedObject.toString());
}
//Highlight
if (searchString != null && !searchString.isEmpty())
{
TextViewHighlighter.highlight(holder, searchString);
}
}
private void bindCourseViewHolder(final CourseViewHolder courseViewHolder, final CatalogCourse course) {
courseViewHolder.name_textView.setText(course.name);
courseViewHolder.viewNb_textView.setText(course.views != null ? course.views.toString() : "0");
if (course.elementCount == null) {
courseViewHolder.counterLinear.setVisibility(View.GONE);
} else {
courseViewHolder.counterLinear.setVisibility(View.VISIBLE);
courseViewHolder.questionNb_textView.setText(
course.elementCount.questions != null ? course.elementCount.questions.toString() : "0");
courseViewHolder.mediaNb_textView.setText(
course.elementCount.medias != null ? course.elementCount.medias.toString() : "0");
courseViewHolder.sheetNb_textView.setText(
course.elementCount.sheets != null ? course.elementCount.sheets.toString() : "0");
}
imageManagerFactory.course(course.id).thumbnail(courseViewHolder.pic_imageView);
//new CourseImageManager(course.id).load(courseViewHolder.pic_imageView);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override public void onClick(View view) {
flowController.routeToCourse(course.id);
}
};
courseViewHolder.container.setOnClickListener(clickListener);
if (course.canBeOffline) {
courseViewHolder.downloadBlock.setVisibility(View.VISIBLE);
DownloadState state = downloadCenter.getCourseStatus(course.id);
LogDev.i(TAG, "can be offline " + state.name());
if (state == DownloadState.DOWNLOADING) {
updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADING);
}
if (state == DownloadState.TO_DOWNLOAD) {
updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADABLE);
}
if (state == DownloadState.DOWNLOADED || state == DownloadState.DOWNLOADED_WITH_SHARED_MODE) {
updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADED);
} else {
DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
#Override public void started() {
LogDev.i(TAG, "started");
mainThreadHandler.post(new Runnable() {
#Override public void run() {
updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADING);
}
});
}
#Override public void finished() {
mainThreadHandler.post(new Runnable() {
#Override public void run() {
updateDownloadBlock(courseViewHolder, DownloadableStatus.DOWNLOADED);
}
});
}
#Override public void error(Exception e) {
mainThreadHandler.post(new Runnable() {
#Override public void run() {
updateDownloadBlock(courseViewHolder, DownloadableStatus.ERROR);
}
});
}
};
downloadCenter.subscribe(course.id, statusCallback);
courseViewHolder.downloadBlock.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v) {
new Thread() {
#Override public void run() {
super.run();
try {
downloadCenter.downloadCourse(course.id, null);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
});
}
} else {
LogDev.i(TAG, "can't be offline");
courseViewHolder.downloadBlock.setVisibility(View.INVISIBLE);
}
}
private void updateDownloadBlock(CourseViewHolder courseViewHolder, DownloadableStatus status) {
if (status == null) return;
courseViewHolder.downloadBlock.setVisibility(
status.equals(DownloadableStatus.NOT_DOWNLOADABLE) ? View.GONE : View.VISIBLE);
courseViewHolder.downloadImage.setVisibility(
status.equals(DownloadableStatus.DOWNLOADABLE) ? View.VISIBLE : View.GONE);
courseViewHolder.downloadProgress.setVisibility(
status.equals(DownloadableStatus.DOWNLOADING) ? View.VISIBLE : View.GONE);
courseViewHolder.downloadedImage.setVisibility(
status.equals(DownloadableStatus.DOWNLOADED) ? View.VISIBLE : View.GONE);
courseViewHolder.downloadErrImage.setVisibility(
status.equals(DownloadableStatus.ERROR) ? View.VISIBLE : View.GONE);
}
private enum DownloadableStatus {
NOT_DOWNLOADABLE, DOWNLOADABLE, DOWNLOADING, DOWNLOADED, ERROR
}
private void bindProgramViewHolder(ProgramViewHolder programViewHolder, final CatalogProgram program) {
imageManagerFactory.program(program.id).thumbnail(programViewHolder.pic_imageView);
//new ProgramImageManager(program.id).load(programViewHolder.pic_imageView);
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override public void onClick(View view) {
flowController.routeToProgram(program.id);
}
};
programViewHolder.container.setOnClickListener(onClickListener);
programViewHolder.pic_imageView.setOnClickListener(onClickListener);
programViewHolder.title_textView.setText(program.name);
programViewHolder.viewCount_textView.setText(program.views != null ? program.views.toString() : "0");
}
private void bindUserViewHolder(UserViewHolder userViewHolder, final FilterableUser user) {
userViewHolder.name_textView.setText(user.name);
userViewHolder.job_textView.setText(user.description);
imageManagerFactory.user(user.id).thumbnail(userViewHolder.pic_imageView);
//new UserImageManager(user.id).loadProfilePic(userViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(),
// true);
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override public void onClick(View view) {
flowController.routeToUser(user.id);
}
};
userViewHolder.pic_imageView.setOnClickListener(onClickListener);
userViewHolder.container.setOnClickListener(onClickListener);
}
private void bindMediaViewHolder(MediaViewHolder mediaViewHolder, final CatalogMedia media) {
imageManagerFactory.media(media.id, media.type, media.extention).symbolOnThumbnail(mediaViewHolder.complex);
//new MediaImageManager(media).load(mediaViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(), false);
mediaViewHolder.title_textView.setText(media.title);
mediaViewHolder.authorName_textView.setText(media.authorName);
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override public void onClick(final View view) {
flowController.routeToDocument(media.id);
}
};
mediaViewHolder.complex.setOnClickListener(onClickListener);
mediaViewHolder.container.setOnClickListener(onClickListener);
}
private void bindGroupViewHolder(GroupViewHolder groupViewHolder, final FilterableGroup group) {
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override public void onClick(View view) {
flowController.routeToGrouop(group.id);
}
};
groupViewHolder.pic_imageView.setOnClickListener(onClickListener);
groupViewHolder.container.setOnClickListener(onClickListener);
groupViewHolder.name_textView.setText(group.name);
String str = resourcesStringRepository.getQuantityString(R.plurals.catalog_group_stat_program,
group.nbProgramsRunning, group.nbProgramsRunning);
str += " - " + resourcesStringRepository.getQuantityString(R.plurals.catalog_group_stat_user, group.nbUser,
group.nbUser);
groupViewHolder.stats_textView.setText(str);
imageManagerFactory.group(group.id).thumbnail(groupViewHolder.pic_imageView);
//new GroupImageManager(group.id).load(groupViewHolder.pic_imageView, NetworkUtils.isNetworkAvailable(), true);
}
#Override public int getItemCount() {
return displayedList.size();
}
}
It is recycling the views.So while clicking the button you have to store its position and change views accordingly.
Maintain a position storing variable globally like this
private int itemClicked=-1;
While clicking the view store the position into itemclicked
holder.button1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
itemclicked=position;
assyncCall(statusCallback);
}
});
Then while updating views check if the position is same like this
if(position==itemclicked){
//show download for clicked view
}else{
//show download stopped for other views
}
Solution
As Surender and Trickcy Solution suggested, I updated the presented data and then tell the adapter to update the cell accordingly :
DownloadStatusCallback statusCallback = new DownloadStatusCallback() {
#Override public void started() {
LogDev.i(TAG, "started");
course.downloadState = DownloadState.DOWNLOADING;
final int position = courseViewHolder.getAdapterPosition();
mainThreadHandler.post(new Runnable() {
#Override public void run() {
notifyItemChanged(position);
}
});
}
#Override public void finished() {
course.downloadState = DownloadState.DOWNLOADED;
final int position = courseViewHolder.getAdapterPosition();
mainThreadHandler.post(new Runnable() {
#Override public void run() {
notifyItemChanged(position);
}
});
}
#Override public void error(Exception e) {
course.downloadState = DownloadState.ERROR_WHILE_DOWNLOADING;
final int position = courseViewHolder.getAdapterPosition();
mainThreadHandler.post(new Runnable() {
#Override public void run() {
notifyItemChanged(position);
}
});
}
};

Recycler View showing wrong data when scrolled fast.Have Added Images For The Same

I have a RecycleView where i have three different views for cells. Data is shown perfectly when RView is loaded for the first time. As I start to scroll, it changes the view color. Tried different ways but not able to resolve it.
original view.
wrong view
public class TimelineRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int DATE_LAYOUT = 1;
private static final int EVEN_LAYOUT = 2;
private static final int ODD_LAYOUT = 3;
private List<TimeLineResponseDO.content> contents = new ArrayList<>();
Context context;
LayoutInflater layoutInflater;
private boolean isVisible = false;
private ConnectionDetector connectionDetector;
private ProgressDialog progressDialog;
private Fragment fragment1;
DateFormat inputFormat;
DateFormat outputFormat;
int counterOnCreate = 0;
int counterOnBind = 0;
public interface OpenSubmissionDetails{
void openSubmissionDetails(String submissionId);
}
public interface IGetTimeLineData {
void getTimeLineData(String date);
void loadSnackBar(String msg);
}
public ProgressDialog getProgressDialog(Context context){
if (progressDialog == null) {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setMessage(context.getString(R.string.loading_message));
}
return progressDialog;
}
IGetTimeLineData getTimeLineData;
public IGetTimeLineData getGetTimeLineData() {
return getTimeLineData;
}
public void setGetTimeLineData(IGetTimeLineData getTimeLineData) {
this.getTimeLineData = getTimeLineData;
}
OpenSubmissionDetails openSubmissionDetails;
public OpenSubmissionDetails getOpenSubmissionDetails() {
return openSubmissionDetails;
}
public void setOpenSubmissionDetails(OpenSubmissionDetails openSubmissionDetails) {
this.openSubmissionDetails = openSubmissionDetails;
}
public TimelineRecyclerAdapter(List<TimeLineResponseDO.content> contents, Context context, Fragment fragment, IGetTimeLineData iGetTimeLineData) {
this.contents = contents;
this.context = context;
this.fragment1 = fragment;
this.getTimeLineData = iGetTimeLineData;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
connectionDetector = new ConnectionDetector(context);
}
public class TimelineDateHolder extends RecyclerView.ViewHolder{
Button date;
public TimelineDateHolder(View convertView) {
super(convertView);
date = (Button) convertView.findViewById(R.id.date);
}
public void bindViews(TimeLineResponseDO.content response){
Date date1 = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("DD-MM-yyyy");
long dateLong = System.currentTimeMillis();
String da = simpleDateFormat.format(dateLong);
Log.e(" Date is :- ", da);
if (response.getDate().equals(da)){
date.setText("Today");
}
else {
if (!TextUtils.isEmpty(response.getDate()))
date.setText(response.getDate());
}
}catch (Exception e){
e.printStackTrace();
if (!TextUtils.isEmpty(response.getDate()))
date.setText(response.getDate());
}
}
}
public class TimelineRecyclerEvenHolder extends RecyclerView.ViewHolder{
RelativeLayout evenContainer;
TextView subjectTypeEven, timingEven, subjectEven, locationEven, teacherEven, cancelTextEven;
Button submissionEven, notificationEven ,submissionEvenDetails ;
ImageView pointerEven, imgCancelBtnEven, imgDelayBtnEven, imgNotificationBtnEven;
View verticalLine;
public TimelineRecyclerEvenHolder(View convertView) {
super(convertView);
evenContainer = (RelativeLayout) convertView.findViewById(R.id.evenContainer);
subjectTypeEven = (TextView) convertView.findViewById(R.id.subjectTypeEven);
timingEven = (TextView) convertView.findViewById(R.id.timingEven);
subjectEven = (TextView) convertView.findViewById(R.id.subjectEven);
locationEven = (TextView) convertView.findViewById(R.id.locationEven);
teacherEven = (TextView) convertView.findViewById(R.id.teacherEven);
pointerEven = (ImageView) convertView.findViewById(R.id.circleEven);
submissionEven = (Button) convertView.findViewById(R.id.submissionEven);
submissionEvenDetails = (Button) convertView.findViewById(R.id.submissionEvenDetails);
imgCancelBtnEven = (ImageView) convertView.findViewById(R.id.cancelBtnEven);//#sp 29-09-2016 added
imgDelayBtnEven = (ImageView) convertView.findViewById(R.id.delayBtnEven);//#sp 30-09-2016 added
imgNotificationBtnEven = (ImageView) convertView.findViewById(R.id.notificationBtnEven);//#sp 30-09-2016 added
notificationEven = (Button) convertView.findViewById(R.id.notificationEven);//#sp 04-10-2016 added
cancelTextEven = (TextView) convertView.findViewById(R.id.cancelTextEven);
subjectTypeEven.setTypeface(NotifyApplication.getExoSemiBold(context));
timingEven.setTypeface(NotifyApplication.getExoSemiBold(context));
subjectEven.setTypeface(NotifyApplication.getExoSemiBold(context));
locationEven.setTypeface(NotifyApplication.getExoSemiBold(context));
teacherEven.setTypeface(NotifyApplication.getExoSemiBold(context));
cancelTextEven.setTypeface(NotifyApplication.getExoSemiBold(context));
}
public void bindViews(TimeLineResponseDO.content response, TimelineRecyclerEvenHolder holder){
holder.evenContainer.setVisibility(View.VISIBLE);
if (!TextUtils.isEmpty(response.getSubjectType())) {
holder.subjectTypeEven.setText(response.getSubjectType());
Log.d("Ifeven", "" + response.getSubjectType());
}
if (response.getLectureSubmission().equals(Enum.LectureSubmission.Submission.toString())) {
holder.subjectTypeEven.setText(Enum.LectureSubmission.Submission.toString());
Log.d("ElseIfeven", "" + response.getSubjectType());
}
Log.d("LectureSubmEven", "" + response.getLectureSubmission());
if (!TextUtils.isEmpty(response.getRoomNo()))
holder.locationEven.setText(response.getRoomNo());
if (!TextUtils.isEmpty(response.getSubject()))
holder.subjectEven.setText(response.getSubject());
if (Boolean.valueOf(StorageService.getInstance().getString("IS_STUDENT")))
{
if (!TextUtils.isEmpty(response.getTeacherAbbreviation()))
holder.teacherEven.setText(response.getTeacherAbbreviation());
}
else if (Boolean.valueOf(StorageService.getInstance().getString("IS_TEACHER")))
{
if (!TextUtils.isEmpty(response.getCourse()))
holder.teacherEven.setText(response.getCourse());
}
if (!TextUtils.isEmpty(response.getStartTime() + context.getString(R.string.timelineHypen) + response.getEndTime()))
holder.timingEven.setText(response.getStartTime() + context.getString(R.string.timelineHypen) + response.getEndTime());
holder.pointerEven.setBackgroundResource(R.drawable.timeline_pointer_left);
holder.timingEven.setCompoundDrawablesWithIntrinsicBounds(R.drawable.timeline_timing, 0, 0, 0);
Log.d("resp isSubmission", "" + response.isSubmission());
if (response.isSubmission()) {
holder.submissionEven.setVisibility(View.VISIBLE);
holder.submissionEven.setText(response.getSubmissionCount() + " Submission");
} else {
holder.submissionEven.setVisibility(View.GONE);
}
Log.d("resp Noti", "" + response.isNotiification());
if (response.isNotiification()) {
holder.notificationEven.setVisibility(View.VISIBLE);
} else {
holder.notificationEven.setVisibility(View.GONE);
}
if (response.getLectureSubmission().equals("Submission")) {
holder.submissionEvenDetails.setVisibility(View.VISIBLE);
} else {
holder.submissionEvenDetails.setVisibility(View.GONE);
}
if (response.isCancelled()) {
ChangeFontColorEven(holder);
}
if (response.getSubmissionStatus() != null) {
if (response.getSubmissionStatus().equals("No")) {
ChangeFontColorEven(holder);
}
}
if (response.isEvenLayout()) {
if (response.getLectureSubmission().equals("Submission")) {
holder.imgDelayBtnEven.setImageResource(R.drawable.pencil);
} else {
holder.imgDelayBtnEven.setImageResource(R.drawable.delay);
}
}
if (!TextUtils.isEmpty(response.getTrnLectureId())) {
submissionLoadId(response);
}
holder.notificationEven.setText(response.getNotificationCount() + " Notifications");
if (isVisible) {
if (!response.isDateContainer()) {
if (response.getLectureSubmission().equals("Submission") && !TextUtils.isEmpty(response.getLectureSubmission())) {
if (response.getSubmissionStatus().equals("No")) {
ShowHideEditLectureIconsEven(holder, View.GONE);
} else {
ShowHideEditLectureIconsEven(holder, View.VISIBLE);
}
} else {
if (response.isCancelled()) {
ShowHideEditLectureIconsEven(holder, View.GONE);
} else {
ShowHideEditLectureIconsEven(holder, View.VISIBLE);
}
}
}
}else {
ShowHideEditLectureIconsEven(holder, View.GONE);
}
}
}
public class TimelineRecyclerHolder extends RecyclerView.ViewHolder{
RelativeLayout oddContainer;
TextView subjectTypeOdd, timingOdd, subjectOdd, locationOdd, teacherOdd, tvCancelTextOdd;
Button submissionOdd, notificationOdd , submissionOddDetails;
ImageView pointerOdd, imgCancelBtnOdd, imgDelayBtnOdd, imgNotificationBtnOdd;
View verticalLine;
public TimelineRecyclerHolder(View convertView) {
super(convertView);
oddContainer = (RelativeLayout) convertView.findViewById(R.id.oddContainer);
subjectTypeOdd = (TextView) convertView.findViewById(R.id.subjectTypeOdd);
timingOdd = (TextView) convertView.findViewById(R.id.timingOdd);
subjectOdd = (TextView) convertView.findViewById(R.id.subjectOdd);
locationOdd = (TextView) convertView.findViewById(R.id.locationOdd);
teacherOdd = (TextView) convertView.findViewById(R.id.teacherOdd);
pointerOdd = (ImageView) convertView.findViewById(R.id.circleOdd);
submissionOdd = (Button) convertView.findViewById(R.id.submissionOdd);
submissionOddDetails = (Button) convertView.findViewById(R.id.submissionOddDetails);
imgCancelBtnOdd = (ImageView) convertView.findViewById(R.id.cancelBtnOdd);
imgDelayBtnOdd = (ImageView) convertView.findViewById(R.id.delayBtnOdd);
imgNotificationBtnOdd = (ImageView) convertView.findViewById(R.id.notificationBtnOdd);
notificationOdd = (Button) convertView.findViewById(R.id.notificationOdd);
tvCancelTextOdd = (TextView) convertView.findViewById(R.id.cancelTextOdd);
subjectTypeOdd.setTypeface(NotifyApplication.getExoSemiBold(context));
timingOdd.setTypeface(NotifyApplication.getExoSemiBold(context));
subjectOdd.setTypeface(NotifyApplication.getExoSemiBold(context));
locationOdd.setTypeface(NotifyApplication.getExoSemiBold(context));
teacherOdd.setTypeface(NotifyApplication.getExoSemiBold(context));
tvCancelTextOdd.setTypeface(NotifyApplication.getExoSemiBold(context));
}
public void bindViews(TimeLineResponseDO.content response, TimelineRecyclerHolder holder){
//holder.verticalLine.setVisibility(View.VISIBLE);
holder.oddContainer.setVisibility(View.VISIBLE);
if (!TextUtils.isEmpty(response.getSubjectType())) {
holder.subjectTypeOdd.setText(response.getSubjectType());
}
if (response.getLectureSubmission().equals(Enum.LectureSubmission.Submission.toString())) {
holder.subjectTypeOdd.setText(Enum.LectureSubmission.Submission.toString());
}
if (!TextUtils.isEmpty(response.getRoomNo()))
holder.locationOdd.setText(response.getRoomNo());
if (!TextUtils.isEmpty(response.getSubject()))
holder.subjectOdd.setText(response.getSubject());
if (Boolean.valueOf(StorageService.getInstance().getString("IS_STUDENT")))
{
if (!TextUtils.isEmpty(response.getTeacherAbbreviation()))
holder.teacherOdd.setText(response.getTeacherAbbreviation());
}
else if (Boolean.valueOf(StorageService.getInstance().getString("IS_TEACHER")))
{
if (!TextUtils.isEmpty(response.getCourse()))
holder.teacherOdd.setText(response.getCourse());
}
if (!TextUtils.isEmpty(response.getStartTime() + context.getString(R.string.timelineHypen) + response.getEndTime()))
holder.timingOdd.setText(response.getStartTime() + context.getString(R.string.timelineHypen) + response.getEndTime());
holder.pointerOdd.setBackgroundResource(R.drawable.timeline_pointer_right);
holder.timingOdd.setCompoundDrawablesWithIntrinsicBounds(R.drawable.timeline_timing, 0, 0, 0);
if (response.isSubmission()) {
holder.submissionOdd.setVisibility(View.VISIBLE);
holder.submissionOdd.setText(response.getSubmissionCount() + " Submission");
} else {
holder.submissionOdd.setVisibility(View.GONE);
}
if (response.isNotiification()) {
holder.notificationOdd.setVisibility(View.VISIBLE);
} else {
holder.notificationOdd.setVisibility(View.GONE);
}
if (response.getLectureSubmission().equals("Submission")) {
holder.submissionOddDetails.setVisibility(View.VISIBLE);
} else {
holder.submissionOddDetails.setVisibility(View.GONE);
}
if (response.isCancelled()) {
ChangeFontColor(holder, Enum.LayoutType.Odd);
}
if (response.getSubmissionStatus() != null) {
if (response.getSubmissionStatus().equals("No")) {
ChangeFontColor(holder, Enum.LayoutType.Odd);
}
}
if (response.getLectureSubmission().equals("Submission")) {
holder.imgDelayBtnOdd.setImageResource(R.drawable.pencil);
} else {
holder.imgDelayBtnOdd.setImageResource(R.drawable.delay);
}
if (!TextUtils.isEmpty(response.getTrnLectureId())) {
submissionLoadId(response);
}
holder.notificationOdd.setText(response.getNotificationCount() + " Notifications");
if (isVisible) {
if (!response.isDateContainer()) {
if (response.getLectureSubmission().equals("Submission") && !TextUtils.isEmpty(response.getLectureSubmission())) {
if (response.getSubmissionStatus().equals("No")) {
ShowHideEditLectureIcons(holder, View.GONE);
} else {
ShowHideEditLectureIcons(holder, View.VISIBLE);
}
} else {
if (response.isCancelled()) {
ShowHideEditLectureIcons(holder, View.GONE);
} else {
ShowHideEditLectureIcons(holder, View.VISIBLE);
}
}
}
}else {
ShowHideEditLectureIcons(holder, View.GONE);
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case DATE_LAYOUT:
View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_date_header, parent, false);
return new TimelineDateHolder(convertView);
case EVEN_LAYOUT:
View convertView1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_even_layout_child, parent, false);
return new TimelineRecyclerEvenHolder(convertView1);
default:
View convertView2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.timeline_odd_layout_child, parent, false);
return new TimelineRecyclerHolder(convertView2);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final int itemType = getItemViewType(position);
TimeLineResponseDO.content content = contents.get(position);
switch (itemType){
case DATE_LAYOUT:
((TimelineDateHolder) holder).bindViews(content);
break;
case EVEN_LAYOUT:
((TimelineRecyclerEvenHolder) holder).bindViews(content, (TimelineRecyclerEvenHolder) holder);
break;
default:
((TimelineRecyclerHolder) holder).bindViews(content, (TimelineRecyclerHolder) holder);
break;
}
if (position == (contents.size() - 1)) {
if (connectionDetector.isConnectingToInternet()) {
getTimeLineData.getTimeLineData(content.getContentDate());
}
else {
getTimeLineData.loadSnackBar(context.getString(R.string.no_internet_connection_schedule));
}
}
}
#Override
public int getItemCount() {
return contents.size();
}
#Override
public int getItemViewType(int position) {
if (contents.get(position).isDateContainer()){
return DATE_LAYOUT;
}
else if (contents.get(position).isEvenLayout()){
return EVEN_LAYOUT;
}
else {
return ODD_LAYOUT;
}
}
private void ChangeFontColor(TimelineRecyclerHolder holder, Enum.LayoutType layoutType) {
switch (layoutType){
case Even:
break;
case Odd:
holder.subjectTypeOdd.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.timingOdd.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.pointerOdd.setBackgroundResource(R.drawable.timeline_pointer_right_red);
holder.subjectOdd.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.locationOdd.setVisibility(View.GONE);
holder.teacherOdd.setVisibility(View.GONE);
holder.tvCancelTextOdd.setVisibility(View.VISIBLE);
holder.tvCancelTextOdd.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.submissionOdd.setVisibility(View.GONE);
holder.submissionOddDetails.setVisibility(View.GONE);
break;
}
}
private void ChangeFontColorEven(TimelineRecyclerEvenHolder holder) {
holder.subjectTypeEven.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.timingEven.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.pointerEven.setBackgroundResource(R.drawable.timeline_pointer_left_red);
holder.subjectEven.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.locationEven.setVisibility(View.GONE);
holder.teacherEven.setVisibility(View.GONE);
holder.cancelTextEven.setVisibility(View.VISIBLE);
holder.cancelTextEven.setTextColor(context.getResources().getColor(android.R.color.holo_red_dark));
holder.submissionEven.setVisibility(View.GONE);
holder.submissionEvenDetails.setVisibility(View.GONE);
}
private void ShowHideEditLectureIcons(TimelineRecyclerHolder holder, int visibility) {
holder.imgCancelBtnOdd.setVisibility(visibility);
holder.imgDelayBtnOdd.setVisibility(visibility);
holder.imgNotificationBtnOdd.setVisibility(visibility);
}
private void ShowHideEditLectureIconsEven(TimelineRecyclerEvenHolder holder, int visibility) {
holder.imgCancelBtnEven.setVisibility(visibility);
holder.imgDelayBtnEven.setVisibility(visibility);
holder.imgNotificationBtnEven.setVisibility(visibility);
}
public void editEvent(boolean isVisible) {
this.isVisible = isVisible;
Log.d("Is Visible", String.valueOf(isVisible));
notifyDataSetChanged();
}
public void submission(final TimeLineResponseDO.content timeLineModel) {
final IGetSubmissionDetails iGetSubmissionDetails = new GetSubmissionDetailsBO();
iGetSubmissionDetails.getSubmissionByTrn(context, timeLineModel.getTrnLectureId(), new Response<ArrayList<String>>() {
#Override
public void onSuccess(ArrayList<String> callback) throws IOException {
StorageService.getInstance().putString("SubmissionId", callback.get(0));
FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
NoticeBoard noticeBoard = new NoticeBoard();
Bundle bundle = new Bundle();
bundle.putStringArrayList("submissionIds", callback);
bundle.putString("submissionId",callback.get(0));
bundle.putString("isFrom","submission_view");
noticeBoard.setArguments(bundle);
fragmentTransaction.replace(R.id.container, noticeBoard, NoticeBoard.class.getSimpleName());
fragmentTransaction.addToBackStack(NoticeBoard.class.getSimpleName());
fragmentTransaction.commit();
}
#Override
public void onError(Exception e, int i, String msg) {
Log.d("trnId error",e.toString());
}
});
}
public void submissionLoadId(final TimeLineResponseDO.content timeLineModel) {
final IGetSubmissionDetails iGetSubmissionDetails = new GetSubmissionDetailsBO();
iGetSubmissionDetails.getSubmissionByTrn(context, timeLineModel.getTrnLectureId(), new ResponseNew<ArrayList<String>>() {
#Override
public void onSuccess(ArrayList<String> callback, String id) throws IOException {
for (int i = 0; i < callback.size(); i++){
Log.e("trnId error", id + " " + callback.get(i));
if (AppConstant.initializeDbORReturn(context).isSubmissionIdExists(id, callback.get(i))){
Log.e("Already Exists :- ", id + " " + callback.get(i));
}
else {
AppConstant.initializeDbORReturn(context).insertSubmissionId(id, callback.get(i));
}
}
}
#Override
public void onError(Exception e, int i, String msg) {
}
});
}
private void localTimeLinedb(List<TimeLineResponseDO> callback, Context context) {
for (int i = 0; i < callback.size(); i++) {
TimeLineResponseDO timeLineResponseDO = callback.get(i);
for (int j = 0; j < timeLineResponseDO.getContentList().size(); j++) {
TimeLineResponseDO.content content = timeLineResponseDO.getContentList().get(j);
if (AppConstant.initializeDbORReturn(context).isTimeLineExits(timeLineResponseDO.getDate(),
content.getStaticLectureId(), content.getDate(),
content.getTrnLectureId(), content.getSlotId(), content.getSubject(),
content.getSubmissionId(), content.getLectureSubmission())) {
AppConstant.initializeDbORReturn(context).updateTimeLine(content, timeLineResponseDO.getDate());
} else {
AppConstant.initializeDbORReturn(context).insertIntoTimeLine(content, timeLineResponseDO.getDate());
}
}
}
}
public void getTimeLineData(String date, final Context context, final TimelineRecyclerHolder holder, final Enum.LayoutType even_odd, final Enum.EditLectureType editLectureType) {
inputFormat = new SimpleDateFormat("dd-mm-yyyy");
outputFormat = new SimpleDateFormat("yyyy-mm-dd");
ITimeLine timeLine = new TimeLineBO();
TimeLinePostDO timeLinePostDO = new TimeLinePostDO();
if (date == null) {
if (!TextUtils.isEmpty(StorageService.getInstance().getString("Running_Teacher_Id"))){
timeLinePostDO.setUserId(StorageService.getInstance().getString("Running_Teacher_Id"));
}
else {
timeLinePostDO.setUserId(StorageService.getInstance().getString("NEWUSER_ID"));
}
timeLinePostDO.setUserRoles(StorageService.getInstance().getString("USER_ROLES"));
} else {
if (!TextUtils.isEmpty(StorageService.getInstance().getString("Running_Teacher_Id"))){
timeLinePostDO.setUserId(StorageService.getInstance().getString("Running_Teacher_Id"));
}
else {
timeLinePostDO.setUserId(StorageService.getInstance().getString("NEWUSER_ID"));
}
timeLinePostDO.setUserRoles(StorageService.getInstance().getString("USER_ROLES"));
try {
timeLinePostDO.setDate(outputFormat.format(inputFormat.parse(date)));
} catch (ParseException e) {
e.printStackTrace();
}
}
timeLine.getTimeLineData(context, timeLinePostDO, new Response<List<TimeLineResponseDO>>() {
#Override
public void onSuccess(List<TimeLineResponseDO> callback) {
localTimeLinedb(callback, context);
getProgressDialog(context).dismiss();
switch (editLectureType){
case Cancel:
ChangeFontColor(holder, even_odd);
Toast.makeText(context, "Lecture Cancelled", Toast.LENGTH_SHORT).show();
ShowHideEditLectureIcons(holder, View.GONE);
break;
case Delay:
Toast.makeText(context, "Notification sent for delay", Toast.LENGTH_SHORT).show();
break;
case CreateNotification:
Toast.makeText(context, "Notification sent", Toast.LENGTH_SHORT).show();
break;
}
if (fragment1 instanceof TimeLineFragment){
((TimeLineFragment) fragment1).refreshList();
}
}
#Override
public void onError(Exception e, int i, String msg) {
}
});
}
}
Thanks in advance !
RecyclerViewAdapter recycles its views and thus the behavior is much expected.
When I read your code I saw that you've written if statements without else like :
if (!TextUtils.isEmpty(response.getRoomNo()))
holder.locationEven.setText(response.getRoomNo());
if (!TextUtils.isEmpty(response.getSubject()))
holder.subjectEven.setText(response.getSubject());
These will be reused if the view in the position before the newly loaded view doesn't fulfill that if statement.
Try adding else to your every if statement. By adding else I mean add something like
else {
holder.locationEven.setText("");
}
// OR
else {
holder.locationEven.setVisibility(View.GONE);
}

How to add Native Ads in between my data items?

I have created a recycler view with custom adapter where I want to show native ads in every 3rd position of my items. But whatever I wrote , its overlapping my item and on top of that, native ad is shown. But I don't want this.
public class Event_Discover_Combined_Adapter extends RecyclerView.Adapter<Event_Discover_Combined_Adapter.MyViewHolder> {
private Context context;
private ArrayList<Event_Discover_Combined_Details> beanList;
private int itemCount;
public Event_Discover_Combined_Adapter(Context context, ArrayList<Event_Discover_Combined_Details> beanList, int itemCount) {
this.context = context;
this.beanList = beanList;
this.imageLoader = ImageLoader.getInstance();
this.itemCount = itemCount;
}
//int viewType ;
#Override
public int getItemViewType(int position) {
if (position % 3 == 0) {
return R.layout.native_ad_frame_layout;
} else {
if (beanList.get(position).getType() == ConstantUrl.TYPE_EVENT) {
return R.layout.events_item;
} else {
return R.layout.discover_item;
}
}
}
#Override
public Event_Discover_Combined_Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(viewType, parent, false);
return new MyViewHolder(itemView);
}
public static ImageLoader imageLoader;
#Override
public void onBindViewHolder(final Event_Discover_Combined_Adapter.MyViewHolder holder, int position) {
Event_Discover_Combined_Details bean = beanList.get(position);
if (position % 3 == 0) {
//Ad View
//For Native Ads
AdLoader.Builder builder = new AdLoader.Builder(context, context.getResources().getString(R.string.ADMOB_AD_UNIT_ID));
//if (requestContentAds) {
builder.forContentAd(new NativeContentAd.OnContentAdLoadedListener() {
#Override
public void onContentAdLoaded(NativeContentAd ad) {
NativeContentAdView adView = (NativeContentAdView) getLayoutInflater()
.inflate(R.layout.native_ad_content, null);
populateContentAdView(ad, adView);
holder.frameLayout.removeAllViews();
holder.frameLayout.addView(adView);
}
});
//}
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(context, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
} else {
//Normal View
AppLog.Log("combine", "beanlist" + bean.getType());
if (bean.getType() == ConstantUrl.TYPE_DISCOVER) {
if (!bean.getDiscoverDetails().getIcon().equals(""))
imageLoader.displayImage(bean.getDiscoverDetails().getIcon(),
holder.iv_discover_icon);
holder.tv_author_name.setText(bean.getDiscoverDetails().getAuthor());
holder.item_discover_descrip.setText(bean.getDiscoverDetails().getDescription());
holder.tv_discover_heading.setText(bean.getDiscoverDetails().getTitle());
} else if (bean.getType() == ConstantUrl.TYPE_EVENT) {
if (!bean.getEventDetails().getIcon().equals(""))
imageLoader.displayImage(bean.getEventDetails().getIcon(),
holder.event_icon);
/* holder.item_event_date.setText(bean.getStartDate());
holder.item_event_time.setText(bean.getStartDate());*/
try {
Date date1 = AppUtils.getFormatedDate(bean.getEventDetails().getStartDate());
String event_time = (String) android.text.format.DateFormat.format("EEEE", date1) + " " + context.getString(R.string.at_text) + " " + new SimpleDateFormat("hh:mm aa").format(date1);
// holder.item_event_date.setText((String) android.text.format.DateFormat.format("dd", date1));
holder.item_event_date.setText(event_time);
holder.item_event_time.setText(event_time);
} catch (Exception e) {
e.printStackTrace();
}
holder.item_event_heading.setText(bean.getEventDetails().getName());
holder.item_event_descrip.setText(bean.getEventDetails().getDescription());
}
}
}
#Override
public int getItemCount() {
return itemCount;
}
// int count = 0;
public void setItemCount(int count) {
this.itemCount = count;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//For Discover
public ImageView iv_discover_icon;
MyTextView tv_author_name;
MyTextView item_discover_descrip;
MyTextView_medium tv_discover_heading;
//For Events
public ImageView event_icon;
public MyTextView_medium item_event_time;
MyTextView item_event_date;
MyTextView item_event_descrip;
MyTextView_medium item_event_heading;
//For Native Ads
FrameLayout frameLayout;
public MyViewHolder(final View itemView) {
super(itemView);
//For Discover
iv_discover_icon = (ImageView) itemView.findViewById(R.id.iv_discover_icon);
tv_author_name = (MyTextView) itemView.findViewById(R.id.tv_author_name);
tv_discover_heading = (MyTextView_medium) itemView.findViewById(R.id.tv_discover_heading);
item_discover_descrip = (MyTextView) itemView.findViewById(R.id.item_discover_descrip);
itemView.setOnClickListener(this);
//For Events
event_icon = (ImageView) itemView.findViewById(R.id.event_icon);
item_event_date = (MyTextView) itemView.findViewById(R.id.item_event_date);
item_event_time = (MyTextView_medium) itemView.findViewById(R.id.item_event_time);
item_event_heading = (MyTextView_medium) itemView.findViewById(R.id.item_event_heading);
item_event_descrip = (MyTextView) itemView.findViewById(R.id.item_event_descrip);
itemView.setOnClickListener(this);
//For Native Ads
frameLayout = (FrameLayout) itemView.findViewById(R.id.fl_adplaceholder);
}
#Override
public void onClick(View v) {
if ((beanList.get(getAdapterPosition()).getType()) == ConstantUrl.TYPE_EVENT) {
Intent i = new Intent(context, Events.class);
i.putExtra("event_details", beanList.get(getAdapterPosition()).getEventDetails());
context.startActivity(i);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(beanList.get(getAdapterPosition()).getDiscoverDetails().getUrl()));
context.startActivity(intent);
}
}
}
private LayoutInflater getLayoutInflater() {
AppLog.Log("classmate5", "inside_getLayoutInflater" + LayoutInflater.from(context));
return LayoutInflater.from(context);
}
private void populateContentAdView(NativeContentAd nativeContentAd,
NativeContentAdView adView) {
AppLog.Log("classmate5", "inside_populateContentAdView");
adView.setHeadlineView(adView.findViewById(R.id.contentad_headline));
adView.setImageView(adView.findViewById(R.id.contentad_image));
adView.setBodyView(adView.findViewById(R.id.contentad_body));
//adView.setCallToActionView(adView.findViewById(R.id.contentad_call_to_action));
//adView.setLogoView(adView.findViewById(R.id.contentad_logo));
//adView.setAdvertiserView(adView.findViewById(R.id.contentad_advertiser));
// Some assets are guaranteed to be in every NativeContentAd.
((MyTextView_medium) adView.getHeadlineView()).setText(nativeContentAd.getHeadline());
((MyTextView) adView.getBodyView()).setText(nativeContentAd.getBody());
//((TextView) adView.getCallToActionView()).setText(nativeContentAd.getCallToAction());
//((TextView) adView.getAdvertiserView()).setText(nativeContentAd.getAdvertiser());
List<NativeAd.Image> images = nativeContentAd.getImages();
if (images.size() > 0) {
((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable());
}
// Some aren't guaranteed, however, and should be checked.
//NativeAd.Image logoImage = nativeContentAd.getLogo();
/*if (logoImage == null) {
//adView.getLogoView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getLogoView()).setImageDrawable(logoImage.getDrawable());
//adView.getLogoView().setVisibility(View.VISIBLE);
}*/
// Assign native ad object to the native view.
adView.setNativeAd(nativeContentAd);
}
}
I want to know where to add a check to hide and unhide the items. Lets say I got 6 items. So, in the recyclerview it should show 9 items including the native ads. (every 3rd position).
if (position == 0 || (position + 1) % 3 == 0) { //add your nativeAdd here }

Categories

Resources