Changing Button image after response from server - android

Am working on an App in which implements a FOLLOW Button inside a View-pager.
when the user clicks the FOLLOW Button the button should change to FOLLOWING after getting success response from the server.
Although i have implemented it ...The button image doesn't change after the click.it has a very unusual behavior.
It sometimes shows FOLLOWING after the activity is reloaded or the pager slides.
Below is my code..
package comend.com.comendify.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import comend.com.comendify.R;
import comend.com.comendify.activity.ActViewUserProfile;
import comend.com.comendify.models.Home;
import comend.com.comendify.models.Tags;
import comend.com.comendify.models.User;
import comend.com.comendify.serverCommunication.WebServerSetGetUserActivities;
import comend.com.comendify.utility.RoundedImageView;
import comend.com.comendify.utility.UserJSONUtils;
import comend.com.comendify.utility.Utils;
/**
* Created by qamar on 14-03-2016.
*/
public class ImageViewPagerAdapter extends PagerAdapter {
public static final String TAG = ImageViewPagerAdapter.class.getSimpleName();
Context mContext;
LayoutInflater mLayoutInflater;
private ArrayList<String> imageList;
private ArrayList<Home> home_arrayList;
private String loggedInUserId;
private Button btnFollow,btnUnFollow;
int resourceId;
int START_INDEX;
private User userLogged;
private View itemView ;
Boolean val =true;
private boolean isFollowing = true;
boolean isIconChange;
public ImageViewPagerAdapter(Context context, ArrayList<String> imageList, int START_INDEX, int resoursceId, ArrayList<Home> home_arrayList) {
mContext = context;
this.imageList =imageList;
this.home_arrayList = home_arrayList;
this.resourceId = resoursceId;
this.START_INDEX = START_INDEX;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
loggedInUserId = Utils.getLoggedInUserId(mContext);
Log.d(TAG,"In ImageViewAdapter: " +START_INDEX+" "+home_arrayList);
}
#Override
public int getCount() {
if(resourceId == R.layout.item_show_image_pager) {
return imageList.size();
}
return home_arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
if(resourceId == R.layout.item_home_pager_profile){
return view ==((RelativeLayout)object);
}
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
Log.d(TAG,"In InstantiateItem" + position);
if(resourceId == R.layout.item_show_image_pager) {
itemView = mLayoutInflater.inflate(R.layout.item_show_image_pager, container, false);
Log.d(TAG, "In viewImage " + position + " " + START_INDEX);
ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_asi_image);
Picasso.with(mContext).load(imageList.get(position))
.fit()
.centerCrop()
.error(R.drawable.logo_splash)
.into(imageView);
container.addView(itemView);
}else if(resourceId == R.layout.item_home_pager_header){
Log.d(TAG, "In homeImageHeader " + position + " " + START_INDEX);
itemView = mLayoutInflater.inflate(R.layout.item_home_pager_header, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_home_image_header);
Picasso.with(mContext).load(String.valueOf(home_arrayList.get(position).getEnt_image()))
.fit()
.centerCrop()
.error(R.drawable.logo_splash)
.into(imageView);
container.addView(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int fragId = 2;
Intent intent = new Intent(mContext, ActViewUserProfile.class);
intent.putExtra("item_id", home_arrayList.get(position).ent_id);
intent.putExtra("frag_id", fragId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show();
}
});
}else if(resourceId == R.layout.item_home_pager_profile){
//here is the problem in yhis layout
Log.d(TAG, "In homeUserProfile " +home_arrayList);
itemView = mLayoutInflater.inflate(R.layout.item_home_pager_profile,container,false);
//function for setting all the elements of item
setUserCommends(itemView, position);
container.addView(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG,"In ItemView Clicked");
int fragId = 3;
Intent intent = new Intent(mContext, ActViewUserProfile.class);
intent.putExtra("commend_id", home_arrayList.get(position).getUser_commend_id());
intent.putExtra("frag_id", fragId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show();
}
});
}
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
if(resourceId ==R.layout.item_show_image_pager) {
container.removeView((LinearLayout) object);
}else if(resourceId == R.layout.item_home_pager_profile){
container.removeView((RelativeLayout)object);
//container.removeViewAt(position);
Log.d(TAG,"In destroy Item " +container.getChildCount());
}
}
//method for setting all the elements
private void setUserCommends(View itemView, final int position){
Log.d(TAG,"In homeprofile setUserCommends " +position );
//Log.d(TAG,"In homeProfile1" +home_arrayList.get(position).getUser_product_image() +" "+home_arrayList.get(position).getUser_image());
ImageView ivProductImage = (ImageView) itemView.findViewById(R.id.iv_hpp_product_pic);
TextView tvProductName = (TextView) itemView.findViewById(R.id.tv_hpp_product_name);
TextView tvProductDesc = (TextView) itemView.findViewById(R.id.tv_hpp_description);
RoundedImageView ivUserImage = (RoundedImageView) itemView.findViewById(R.id.iv_hpp_user_profile_pic);
TextView tvUserName = (TextView) itemView.findViewById(R.id.tv_hpp_profile_name);
btnFollow = (Button) itemView.findViewById(R.id.btn_hpp_follow);
// btnUnFollow = (Button) itemView.findViewById(R.id.btn_hpp_unfollow);
userLogged = new User();
userLogged.setmUserName(home_arrayList.get(position).getUser_name());
userLogged.setmImageUrl(home_arrayList.get(position).getUser_image());
userLogged.setmFirstName(home_arrayList.get(position).getUser_name());
//checking for the buttons for each slides or when the screen first turns up
if(home_arrayList.get(position).getIs_following()== 0){
Log.d(TAG, "In check if " + home_arrayList.get(position).getIs_following());
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_follow, 0, 0, 0);
}else{
Log.d(TAG, "In check else " + home_arrayList.get(position).getIs_following());
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_following, 0, 0, 0);
}
if(!home_arrayList.get(position).getUser_product_image().isEmpty()) {
setImageWithPicasso(ivProductImage, home_arrayList.get(position).getUser_product_image());
}
if(!home_arrayList.get(position).getUser_image().isEmpty()){
setImageWithPicasso(ivUserImage, home_arrayList.get(position).getUser_image());
}
tvProductName.setText(home_arrayList.get(position).getUser_product_name());
tvProductDesc.setText(home_arrayList.get(position).getUser_commend_review());
tvUserName.setText(home_arrayList.get(position).getUser_name());
ivUserImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG,"In userImage Clicked");
int fragId = 1;
Intent intent = new Intent(mContext, ActViewUserProfile.class);
intent.putExtra("user_id", home_arrayList.get(position).getUser_id());
intent.putExtra("frag_id", fragId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show();
}
});
//isFollowing = false;
//puttong the clickListener on the follow button
btnFollow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG,"In btnFollow Clicked");
//isIconC =!isIconChange;
if (isFollowing =true) {
Log.d(TAG, "in isFollowing");
isFollowing =false;
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_follow, 0, 0, 0);
unFollowUser(home_arrayList.get(position).getUser_id(), position);
} else {
Log.d(TAG, "in isNotFollowing");
isFollowing = true;
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_following, 0, 0, 0);
btnFollow.setText("UNFOLLOW");
//btnFollow.setEnabled(false);
followerUser(home_arrayList.get(position).getUser_id(), position);
}
}
});
}
private void setImageWithPicasso(ImageView imageView, String user_product_image){
Picasso.with(mContext).load(user_product_image)
.fit()
.centerCrop()
.error(R.drawable.logo_splash)
.into(imageView);
}
//Method for Following user
private void followerUser(String user_id, int position) {
final int FOLLOW_TAG = 0;
UserJSONUtils userJSONUtils = new UserJSONUtils(mContext);
String json =userJSONUtils. setDataToJson(userLogged,user_id);
//call the method to follow
callToServerToFollow(json, FOLLOW_TAG,position);
}
//method for UnFollowing user
private void unFollowUser(String user_id, int position){
final int UNFOLLOW_TAG = 1;
UserJSONUtils userJSONUtils = new UserJSONUtils(mContext);
String json = userJSONUtils.setDataToJson(userLogged,user_id);
//calling the method to follow
callToServerToFollow(json, UNFOLLOW_TAG,position);
}
// method for calling server
public void callToServerToFollow(String json,int TAG_FOLL,int position){
WebServerSetGetUserActivities webServerSetGetUserActivities = new WebServerSetGetUserActivities(mContext,btnFollow,btnUnFollow,null,null);
webServerSetGetUserActivities.addFollowUnFollow(json, TAG_FOLL, Tags.ACT_TAG.ACT_HOME_FEED,home_arrayList,position);
}
}
really appreciate any help.

Note, Fragments state on ViewPager are being initialize a Fragment before.
that is if three fragments A,B,C are use on ViewPager, B state is initialize on A while on user view, C also those the same when B is on user View.
There are two way to solve this
1) use A Fragment to implement the request method for response and set a public boolean to get response result true, then on B fragment where the button event is needed, check for boolean result.
2) In your AppController class check for result from A fragment and set to B fragment. This will always keep the result as it is even when the app is onPause.
check this http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ for implementing AppController class.

Related

Android RecyclerView and custom Adapter position elements changes

I have a RecylcerView filled with a Custom Adapter recylerView.setAdapter(myAdapter), and the adaper is filled with different elements by an ArrayList. In the ViewHolder i overrided the
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) method. In the custom ViewHolder i put a button. The button has a click listener on it. When i click the button i read the variable position and i am facing that the variable changes every time i click the same button.
Why this happens?
My Adapter is like this:
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.amplifyframework.core.Amplify;
import com.amplifyframework.core.model.query.Where;
import com.amplifyframework.datastore.generated.model.Comments;
import com.amplifyframework.datastore.generated.model.Likes;
import com.amplifyframework.datastore.generated.model.Posts;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import java.net.URL;
import java.util.LinkedList;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread;
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.PostViewHolder>
{
private LinkedList<Posts> usersPostsList;
private FirebaseAuth mAuth;
private Context context;
//private Boolean likeChecker;
private String currentUserId;
private MainActivity mainActivity;
private int currentPosition;
public PostsAdapter(Context context, String currentUserId, MainActivity mainActivity)
{
this.context = context;
this.currentUserId = currentUserId;
this.mainActivity = mainActivity;
}
public PostsAdapter(LinkedList<Posts> usersPostsList, Context context)
{
this.usersPostsList = usersPostsList;
this.context = context;
}
public void setMessages(LinkedList<Posts> usersPostsList) {
this.usersPostsList = usersPostsList;
}
public static class PostViewHolder extends RecyclerView.ViewHolder
{
View mView;
public static ImageButton LikePostButton, CommentPostButton;
public TextView DisplayNoOfLikes, modifyPost;
private TextView DisplayNoOfComments;
String currentUserID;
ExpandableTextView PostDescription;
private Context context;
public PostViewHolder(#NonNull View itemView, Context context)
{
super(itemView);
mView = itemView;
this.context = context;
LikePostButton = (ImageButton) mView.findViewById(R.id.like_button);
CommentPostButton = (ImageButton) mView.findViewById(R.id.comment_button);
DisplayNoOfLikes = (TextView) mView.findViewById(R.id.display_no_of_likes);
DisplayNoOfComments = (TextView) mView.findViewById(R.id.display_no_of_comments);
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
modifyPost = mView.findViewById(R.id.modify_post);
}
public void setLikeButtonStatus(final String PostKey) {
Amplify.DataStore.query(
Likes.class, Where.matches(Likes.POST_ID.eq(PostKey.trim()).and(Likes.SENDER.eq(currentUserID.trim()))),
items -> {
int countLikes = 0;
if (!items.hasNext()) {
LikePostButton.setImageResource(R.drawable.ic_star_border);
}
while (items.hasNext()) {
Likes item = items.next();
countLikes++;
LikePostButton.setImageResource(R.drawable.ic_star_fill);
Log.i("Amplify", "Id " + item.getId());
}
int finalCountLikes = countLikes;
DisplayNoOfLikes.setText(finalCountLikes + (" Likes"));
},
failure -> Log.e("Amplify", "Could not query DataStore", failure)
);
}
public void setFullname(String fullname)
{
TextView username = (TextView) mView.findViewById(R.id.post_user_name);
username.setText(fullname);
}
public void setProfileimage(Context ctx, String profileimage)
{
CircleImageView image = (CircleImageView) mView.findViewById(R.id.post_profile_image);
Amplify.Storage.getUrl(profileimage,
result -> {
URL url = result.getUrl();
runOnUiThread(() -> Glide.with(ctx)
.load(url)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(image));
},
error -> Log.i("Amplify", "error while retrieving url"));
}
public void setTime(String time)
{
TextView PostTime = (TextView) mView.findViewById(R.id.post_time);
PostTime.setText(" " + time);
}
public void setDate(String date)
{
TextView PostDate = (TextView) mView.findViewById(R.id.post_date);
PostDate.setText(" " + date);
}
public void setDescription(String description)
{
PostDescription = mView.findViewById(R.id.post_description);
PostDescription.setText(description);
}
public void setPostimage(Context ctx, String postimage, String id)
{
ImageView postImageInner = mView.findViewById(R.id.post_image);
Amplify.Storage.getUrl(postimage,
result -> {
URL url = result.getUrl();
runOnUiThread(() -> Glide.with(ctx)
.load(url)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(postImageInner));
Log.i("Amplify---------", "url ok----");
},
error -> Log.e("Amplify---------", "error while retrieving url: " + error.getCause().toString()));
postImageInner.setOnClickListener(v -> {
Intent clickPostIntent = new Intent(context, ClickPostActivity.class);
clickPostIntent.putExtra("PostKey", id);
clickPostIntent.putExtra("postImagePath", postimage);
context.startActivity (clickPostIntent);
});
}
public void setCountry(String country)
{
TextView CountryName = (TextView) mView.findViewById(R.id.post_country_name);
CountryName.setText(country);
}
public void setCity(String city)
{
TextView City = (TextView) mView.findViewById(R.id.post_city_name);
City.setText("- " + city);
}
public void setCommentStatus(final String PostKey) {
Amplify.DataStore.query(
Comments.class, Where.matches(Comments.POST_ID.eq(PostKey.trim())),
items -> {
int i = 0;
while (items.hasNext()) {
Comments comments = items.next();
i++;
int finalI = i;
runOnUiThread(() -> DisplayNoOfComments.setText(finalI + " comments"));
Log.i("amplify?", "comment id: " + comments.getId());
}
},
failure -> Log.e("Amplify", "Could not query DataStore", failure)
);
}
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View V = LayoutInflater.from(parent.getContext())
.inflate(R.layout.all_posts_layout, parent,false);
mAuth = FirebaseAuth.getInstance();
return new PostViewHolder(V, context);
}
#Override
public int getItemViewType(int position) {
currentPosition = position;
return position;
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder viewHolder, int position) {
viewHolder.setFullname(usersPostsList.get(position).getFullname());
viewHolder.setTime(usersPostsList.get(position).getTime());
viewHolder.setDate(usersPostsList.get(position).getDate());
viewHolder.setDescription(usersPostsList.get(position).getDescription());
viewHolder.setProfileimage(context, usersPostsList.get(position).getProfileimage());
viewHolder.setPostimage(context, usersPostsList.get(position).getPostimage(), usersPostsList.get(position).getId());
viewHolder.setCountry(usersPostsList.get(position).getCountry());
viewHolder.setCity(usersPostsList.get(position).getCity());
if( viewHolder.PostDescription.originalText.length() > 100 ) {
viewHolder.PostDescription.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!((ExpandableTextView)v).read) {
((ExpandableTextView)v).expandText();
((ExpandableTextView)v).read = true;
} else {
((ExpandableTextView)v).truncateText();
((ExpandableTextView)v).read = false;
}
}
});
}
viewHolder.CommentPostButton.setOnClickListener(v -> {
Intent commentsIntent = new Intent(context, CommentActivity.class);
commentsIntent.putExtra("PostKey",usersPostsList.get(currentPosition).getId());
context.startActivity(commentsIntent);
});
viewHolder.LikePostButton.setOnClickListener(v -> {
Amplify.DataStore.query(
Likes.class, Where.matches(Likes.POST_ID.eq(usersPostsList.get(currentPosition).getId().trim())
.and(Likes.SENDER.eq(currentUserId.trim()))
.and((Likes.RECEIVER.eq(usersPostsList.get(currentPosition).getUid())))
),
items -> {
if (items.hasNext()) {
Likes item = items.next();
Amplify.DataStore.delete(item,
deleted -> Log.i("Amplify", "Deleted item."),
failure -> Log.e("Amplify", "Delete failed.", failure)
);
Log.i("Amplify", "Id " + item.getId());
} else {
Likes likes = Likes.builder()
.receiver(usersPostsList.get(currentPosition).getUid().trim())
.sender(currentUserId.trim())
.postId(usersPostsList.get(currentPosition).getId().trim())
.value("true")
.build();
Amplify.DataStore.save(
likes,
success -> Log.i("Amplify", "Item updated: " + success.item().getId()),
error -> Log.e("Amplify", "Could not save item to DataStore", error)
);
}
},
failure -> {
Log.e("Amplify", "Could not query DataStore", failure);
}
);
notifyDataSetChanged();
});
viewHolder.modifyPost.setOnClickListener(v -> {
Intent intent = new Intent(context, ClickPostActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("PostKey", usersPostsList.get(currentPosition).getId());
intent.putExtra("postImagePath", usersPostsList.get(currentPosition).getPostimage());
context.startActivity(intent);
});
}
#Override
public int getItemCount() {
return usersPostsList.size() ;
}
}
Seems that method getItemViewType is called after the click on LikePostButton so that : viewHolder.LikePostButton.setOnClickListener(v -> { gets an older currentPosition variable value
Thanks to everyone helping me to understand
you can override getItemViewType(position:Int) method and replace the line of super to return it with only position like this in Kotlin:
override fun getItemViewType(position: Int): Int {
return position
}
in Java :
#Override
public int getItemViewType(int position) {
return position;
}
Thanks, i solved it setting the listener on the button in the ViewHolder and then just calling getAbsoluteAdapterPosition() to get the correct position

How to start activity from onClick on RecyclerView in actvity

Hello Everyone I am trying to start activity when I click on RecyclerView , it is started when I add the code in the Custom Adapter , but when I write it in Activity it Just give me the position on Log ..
so any help
here is the code OnClick in activity and that's what I tried to do
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = v.getContext();
Intent intent = new Intent(context.getApplicationContext() , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.getApplicationContext().startActivity(intent);
finish();
}
here is the activity
package com.abed.montage.hijabapptest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class FrameListActivity extends AppCompatActivity implements PhotoRecyclerViewAdapter.MyClickListener {
private RecyclerView photoRecyclerView;
private RecyclerView.Adapter mAdapter;
private List<Integer> framePhotoList ;
List<PhotoClass> results ;
private static String LOG_TAG = "CardViewActivity";
String positionId ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame_list);
photoRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
photoRecyclerView.setHasFixedSize(true);
int numberOfColumns = 2;
// mLayoutManager = new LinearLayoutManager();
photoRecyclerView.setLayoutManager(new GridLayoutManager(this , numberOfColumns));
mAdapter = new PhotoRecyclerViewAdapter(getDataSet() , this);
photoRecyclerView.setAdapter(mAdapter);
}
#Override
protected void onResume() {
super.onResume();
((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private List<PhotoClass> getDataSet() {
fillPhotoFrameList();
results = new ArrayList<>();
for (int index = 0; index < framePhotoList.size(); index++) {
PhotoClass obj = new PhotoClass();
obj.setImage(framePhotoList.get(index));
results.add(index, obj);
}
return results;
}
private void fillPhotoFrameList(){
framePhotoList = new ArrayList<>();
framePhotoList.add(R.drawable.frame_1);
framePhotoList.add(R.drawable.frame_2);
framePhotoList.add(R.drawable.frame_3);
framePhotoList.add(R.drawable.frame_4);
framePhotoList.add(R.drawable.frame_5);
framePhotoList.add(R.drawable.frame_6);
framePhotoList.add(R.drawable.frame_7);
framePhotoList.add(R.drawable.frame_8);
framePhotoList.add(R.drawable.frame_2);
framePhotoList.add(R.drawable.frame_10);
framePhotoList.add(R.drawable.frame_11);
framePhotoList.add(R.drawable.frame_12);
framePhotoList.add(R.drawable.frame_13);
framePhotoList.add(R.drawable.frame_14);
framePhotoList.add(R.drawable.frame_15);
framePhotoList.add(R.drawable.frame_16);
framePhotoList.add(R.drawable.frame_17);
framePhotoList.add(R.drawable.frame_18);
framePhotoList.add(R.drawable.frame_19);
framePhotoList.add(R.drawable.frame_20);
}
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = v.getContext();
Intent intent = new Intent( context , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.startActivity(intent);
finish();;
}
public String createImageFromBitmap(Bitmap bitmap , String fileNameForSave) {
String fileName = fileNameForSave;//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
}
and here is the Adapter ....
package com.abed.montage.hijabapptest;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.List;
/**
* Created by hp15-AY on 02/27/2017.
*/
public class PhotoRecyclerViewAdapter extends RecyclerView.Adapter<PhotoRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<PhotoClass> mDataset;
private static MyClickListener myClickListener;
Context context;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
ImageView photo;
public DataObjectHolder(View itemView) {
super(itemView);
photo = (ImageView) itemView.findViewById(R.id.photo);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
// Context context = v.getContext();
// Intent intent = new Intent(context, FinalActivity.class);
// context.startActivity(intent);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public PhotoRecyclerViewAdapter(List<PhotoClass> myDataset , Context context) {
this.context = context ;
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_photo, parent, false);
view.setBackgroundResource(R.drawable.rounded_frame);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.photo.setImageBitmap(BitmapFactory.decodeResource(context.getResources() ,mDataset.get(position).getImage()));
}
public void addItem(PhotoClass dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
and here is the class ...
public class PhotoClass {
int id;
int image ;
public PhotoClass() {
}
public void setId(int id) {
this.id = id;
}
public void setImage(int image) {
this.image = image;
}
public int getId() {
return id;
}
public int getImage() {
return image;
}
}
FinalActivity OnCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Activity Created");
setContentView(R.layout.activity_final);
mGlobal = (Global) getApplicationContext();
imageViewThumbnail = (ImageView) findViewById(R.id.selectedimage);
saveIcon = (ImageView) findViewById(R.id.imageSave);
filterIcon = (ImageView) findViewById(R.id.editImage);
mImageViewFrame = (ImageView) findViewById(R.id.frameimage);
// mInterstitialAd = new InterstitialAd(this);
// mInterstitialAd.setAdUnitId(getApplicationContext().getString(R.string.admob_intersitials));
// mAdRequest= new AdRequest.Builder().build();
// mInterstitialAd.loadAd(mAdRequest);
imageViewThumbnail.setOnTouchListener(new MultiTouchListener());
mDialog = Utils.SetProgressBar(mDialog, FinalActivity.this);
mDialog.dismiss();
loadImage(imageViewThumbnail, mGlobal.getPath());
String result = getIntent().getStringExtra("resultpos");
pos = Integer.parseInt(result);
Log.w("Position===", "" + pos);
String imagevalue = frames[pos];
Log.w("imagename=====++++", "" + imagevalue);
int resID = getResources().getIdentifier(imagevalue, "drawable", getPackageName());
mImageViewFrame.setImageResource(resID);
saveIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// }
RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
SaveImage(bm);
}
});
filterIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
EditImage(bm);
}
});}
loadImage Function :
private void loadImage(ImageView iv, final String path) {
if(!isAirplaneModeOn(this.getApplicationContext())) {
Picasso.with(FinalActivity.this)
.load(Uri.fromFile(new File(path)))
.fit()
.centerInside()
.into(iv, new Callback() {
#Override
public void onSuccess() {
Log.i(TAG, "Picasso Success Loading Thumbnail - " + path);
}
#Override
public void onError() {
Log.i(TAG, "Picasso Error Loading Thumbnail Small - " + path);
}
});
}
else{
//do something else?
}
File image = new File(path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
engrave(bitmap);
// bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
}
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static boolean isAirplaneModeOn(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
} else {
return Settings.Global.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
}
I used setOnClickListener in itemView in the onBindViewHolder.
the itemView is like the container of all things that has the item...
public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyClassViewHolder> {
....
....
....
#Override
public void onBindViewHolder(#NonNull final MyClassViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , NewActivity.class);
context.startActivity(intent);
}
});
}
....
....
}
This is another example that I find
I created the setOnClickListener on view in onCreateViewHolder
public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyClassViewHolder> {
....
....
....
#NonNull
#Override
public MyClassViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.row_item_example, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Click in oncReateViewHolder");
}
});
return new SolicitudViewHolder(view);
}
....
....
}
Try this:
in your onResume(): you are already attaching setOnItemClickListener into the PhotoRecyclerViewAdapter
#Override
protected void onResume() {
super.onResume();
((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
Intent intent = new Intent(FrameListActivity.this , FinalActivity.class);
intent.putExtra("resultpos", "" + position);
startActivity(intent);
}
});
}
Use this:
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = FrameListActivity.this;
Intent intent = new Intent(context , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.startActivity(intent);
finish();
}
Hope this helps.
As far as I know, the proper way to attach an onClickListener to a recyclerView, is to do so in the onBindViewHolder method as mentioned as the first option in the answer below. This method binds the properties to each of the recyclerview item, therefore the onClickListener could also be attached similarly.

RecyclerView does not update or refresh when calling notifyDataSetChanged()

I have an app that uses RecyclerView. When user selects "Add New Row" from the options menu, I output a test message to the screen, and some values get appended to two different ArrayLists. That part is working great, as I have confirmed these values are successfully added by looking at the ArrayList values using the debugger.
Anyhow I am not able to get the RecyclerView to redraw the screen and show the new information. My attempt to redraw / update the screen is by using this code (line 78 of MainActivity.java):
//call notify data set changed method for the adapter
adapter.notifyDataSetChanged();
Maybe I am not calling notifyDataSetChanged on the same adapter that actually is used for RecycleView??
Here is the complete code for MainActivity.java (see options menu code at end):
package com.joshbgold.ironmax;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int ADD_ROW = 1; //used for case statement statement to select menu item
private RecyclerView recyclerView;
public Exercises exercises = new Exercises();
public ExerciseRow adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
assert getSupportActionBar() != null;
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.barbell);
actionBar.setTitle(" " + "Iron Max");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//ExerciseRow adapter = new ExerciseRow(this);
adapter = new ExerciseRow(this);
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/* MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_row, menu);
return super.onCreateOptionsMenu(menu);*/
menu.add(0, ADD_ROW, 0, "Add New Row");
menu.getItem(0).setIcon(R.drawable.plus);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(0).setIcon(R.drawable.plus);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int length;
switch (item.getItemId()) {
case 1:
Toast msg = Toast.makeText(MainActivity.this, "Test code for adding an exercise", Toast.LENGTH_LONG);
msg.show();
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
length = exercises.getExercisesArrayLength();
//call notify data set changed method for the adapter
adapter.notifyItemInserted(length - 1);
adapter.notifyDataSetChanged();
return super.onOptionsItemSelected(item);
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is Exercises.java:
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
public class Exercises extends AppCompatActivity {
public ArrayList<String> exercisesArrayList = new ArrayList<>(); //stores all the lifts
private ArrayList<Integer> personalBestsArrayList = new ArrayList<>(); //stores personal bests in pounds
public ArrayList<String> getExercisesArray() { //returns the whole exercises arraylist
return exercisesArrayList;
}
public ArrayList<Integer> getPersonalBests() { //returns the whole personal bests arraylist
return personalBestsArrayList;
}
public String getExercise(int position) { //returns individual exercise from array
return exercisesArrayList.get(position);
}
public void addExercise(String exercise) {
exercisesArrayList.add(exercise);
}
public void removeExercise(int position) {
exercisesArrayList.remove(position);
}
public void editExercise(int position, String exercise) {
exercisesArrayList.set(position, exercise);
}
public int getExercisesArrayLength() {
return exercisesArrayList.size();
}
public Integer getPersonalBest(int position) { //returns individual personal best from array
return personalBestsArrayList.get(position);
}
public void addPersonalBest(int personalBest) {
personalBestsArrayList.add(personalBest);
}
public void removePersonalBest(int position) {
personalBestsArrayList.remove(position);
}
public void editPersonalBest(int position, int personalBest) {
personalBestsArrayList.set(position, personalBest);
}
public Exercises() {} //constructor
}
Here is ExerciseRow.java:
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class ExerciseRow extends RecyclerView.Adapter<ExerciseRow.ExerciseViewHolder> {
String exerciseName = "burpee";
String exercisePR = "100"; // user's personal record for this exercise in pounds
private Context context;
Exercises exercises = new Exercises();
public ExerciseRow(Context context) {
this.context = context;
}
#Override
public ExerciseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.exercise_list_item, parent, false);
return new ExerciseViewHolder(view);
}
#Override
public void onBindViewHolder(ExerciseViewHolder holder, int position) {
ArrayList<String> exercisesArray = exercises.getExercisesArray();
holder.bindExercises(exercisesArray.get(position));
}
#Override
public int getItemCount() {
return exercises.getExercisesArrayLength();
}
public class ExerciseViewHolder extends RecyclerView.ViewHolder {
public TextView exerciseNameTextView;
public TextView personalRecordTextView;
public ImageView edit_Icon;
public ImageView percentages_Icon;
public ImageView trash_Icon;
public ImageView plus_icon;
public ImageView facebook_icon;
public ImageView twitter_icon;
public ExerciseViewHolder(View itemView) {
super(itemView);
exerciseNameTextView = (TextView) itemView.findViewById(R.id.list_item_exercise_textview);
personalRecordTextView = (TextView) itemView.findViewById(R.id.list_item_amount_textview);
edit_Icon = (ImageView) itemView.findViewById(R.id.list_item_pencil);
percentages_Icon = (ImageView) itemView.findViewById(R.id.list_item_percent);
trash_Icon = (ImageView) itemView.findViewById(R.id.list_item_trash);
plus_icon = (ImageView) itemView.findViewById(R.id.list_item_plus);
facebook_icon = (ImageView) itemView.findViewById(R.id.list_item_facebook);
twitter_icon = (ImageView) itemView.findViewById(R.id.list_item_twitter);
View.OnClickListener plus = new View.OnClickListener() {
#Override
public void onClick(View view) {
// allow user to add a new exercise and personal best
exercises.addExercise("Some exercise");
exercises.addPersonalBest(500);
notifyDataSetChanged();
}
};
View.OnClickListener edit = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be edited.", Toast.LENGTH_LONG).show();
}
else{
editRow(position); //edit the row at the current position
notifyDataSetChanged();
}
}
};
View.OnClickListener percentages = new View.OnClickListener() {
#Override
public void onClick(View view) {
//get exercise name
exerciseName = exerciseNameTextView.getText().toString();
exercisePR = personalRecordTextView.getText().toString();
//show percentages layout
startPercentagesActivity(exerciseName, exercisePR);
}
};
View.OnClickListener trash = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getLayoutPosition(); //use getAdapterPosition() if getLayoutPosition causes a problem
if (position == 0) { //prevent user from deleting the first row.
Toast.makeText(context, "Sorry, example row cannot be deleted.", Toast.LENGTH_LONG).show();
} else {
exercises.removeExercise(position);
exercises.removePersonalBest(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, exercises.getExercisesArrayLength());
}
}
};
plus_icon.setOnClickListener(plus);
edit_Icon.setOnClickListener(edit);
percentages_Icon.setOnClickListener(percentages);
trash_Icon.setOnClickListener(trash);
}
public void bindExercises(String exercises) {
Exercises exercisesObject = new Exercises();
exerciseNameTextView.setText(exercisesObject.getExercise(getAdapterPosition()));
personalRecordTextView.setText((exercisesObject.getPersonalBest(getAdapterPosition())).toString() + " pounds");
}
}
private void startPercentagesActivity(String some_exercise, String personal_record) {
Intent intent = new Intent(context, PercentagesActivity.class);
intent.putExtra("exerciseName", some_exercise);
intent.putExtra("personalRecord", personal_record);
context.startActivity(intent);
}
protected void editRow(final int position) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final View textEntryView = layoutInflater.inflate(R.layout.text_entry, null);
final EditText liftName = (EditText) textEntryView.findViewById(R.id.liftNameEditText);
final EditText PersonalBestInPounds = (EditText) textEntryView.findViewById(R.id.personalBestEditText);
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setIcon(R.mipmap.barbell)
.setTitle("Please make your changes:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//retrieve the user's input
String lift = liftName.getText().toString();
int personalBest = Integer.parseInt(PersonalBestInPounds.getText().toString());
//save the user's input to the appropriate arrays
exercises.editExercise(position, lift);
exercises.editPersonalBest(position, personalBest);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
}
}
If you have read this far, I give you credit! Please understand I am completely new to RecyclerView, so whatever error(s) I have made could be something quite simple even.
The issue is that you have two different instances of ExercisesOne in MainActivity and another in ExerciseRow You are adding the data to the wrong one.
A few other things that may help you along your way.
Exercises Should not extend AppCompatActivity (or really anything as far as I can tell)
You should avoid saving a reference to the context (as you are doing in Exercises) it can great memory issues. Instead try one of the following.
A. Use the context to get the LayoutInflater in the constructor
B. Call parent.getContext() in onCreateViewHolder

Save State of RecyclerView

I am making a app with RecylerView populated with data form an online server. It has a custom layout with a favorite button that when clicked the icon changes.I have a problem trying to save state of a selected view on the RecyclerView. The RecyclerView does not save the selected state on scrolling back up. Kindly help.
Model Class
package com.smartdevelopers.kandie.nicedrawer.newsModel;
/**
* Created by 4331 on 25/09/2015.
*/
public class Latest {
public String excerpt;
public String articleImage;
public String articleUrl;
public boolean mfavourite;
public boolean isFavourite(){
return mfavourite;
}
public String getArticleUrl() {
return articleUrl;
}
public void setArticleUrl(String articleUrl) {
this.articleUrl = articleUrl;
}
public String getExcerpt() {
return excerpt;
}
public void setExcerpt(String excerpt) {
this.excerpt = excerpt;
}
public String getArticleImage() {
return articleImage;
}
public void setArticleImage(String articleImage) {
this.articleImage = articleImage;
}
}
Adapter
package com.smartdevelopers.kandie.nicedrawer.newsAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.smartdevelopers.kandie.nicedrawer.R;
import com.smartdevelopers.kandie.nicedrawer.ReadArticleActivity;
import com.smartdevelopers.kandie.nicedrawer.newsModel.Latest;
import com.smartdevelopers.kandie.nicedrawer.util.SharedPreferenceRecycler;
import java.util.HashMap;
import java.util.List;
/**
* Created by 4331 on 29/09/2015.
*/
public class OtherNewsAdapter extends RecyclerView.Adapter<OtherNewsAdapter.ViewHolder> {
private List<Latest> feedItemList;
private Context mContext;
private static final String TAG = "ActivityGplus";
SharedPreferenceRecycler sharedPreference = new SharedPreferenceRecycler();
public OtherNewsAdapter(Context context, List<Latest> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_other_news, null);
ViewHolder mh = new ViewHolder(v);
return mh;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final Latest feedItem = feedItemList.get(i);
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.placeholder)
.showImageOnFail(R.drawable.placeholder)
.showImageOnLoading(R.drawable.placeholder).build();
//download and display image from url
imageLoader.displayImage(feedItem.getArticleImage(), viewHolder.thumbnail, options);
// Glide.with(mContext).load(feedItem.getArticleImage())
// .error(R.drawable.placeholder)
// .placeholder(R.drawable.placeholder)
// .into(viewHolder.thumbnail);
viewHolder.title.setText(Html.fromHtml(feedItem.getExcerpt()));
viewHolder.articleUrl.setText(Html.fromHtml(feedItem.getArticleUrl()));
viewHolder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ReadArticleActivity.class);
intent.putExtra("articleUrl", viewHolder.articleUrl.getText().toString());
mContext.startActivity(intent);
}
});
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if (checkFavoriteItem(feedItem)) {
viewHolder.favImage.setImageResource(R.drawable.heart_red);
viewHolder.favImage.setSelected(true);
viewHolder.favImage.setTag("red");
hashMap.get(i);
}
else {
viewHolder.favImage.setImageResource(R.drawable.heart_grey);
viewHolder.favImage.setSelected(false);
viewHolder.favImage.setTag("grey");
}
viewHolder.title.setTag(viewHolder);
viewHolder.thumbnail.setId(R.id.otherImage);
viewHolder.articleUrl.setTag(viewHolder);
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
OtherNewsRowHolder holder = (OtherNewsRowHolder) view.getTag();
int position = holder.getPosition();
Latest feedItem = feedItemList.get(position);
Toast.makeText(mContext, feedItem.getExcerpt(), Toast.LENGTH_SHORT).show();
}
};
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Latest checkProduct) {
boolean check = false;
List<Latest> favorites = sharedPreference.getFavorites(mContext);
if (favorites != null) {
for (Latest product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView thumbnail, favImage;
protected TextView title,articleUrl;
public ViewHolder(View itemView) {
super(itemView);
this.thumbnail = (ImageView) itemView.findViewById(R.id.otherImage);
this.title = (TextView) itemView.findViewById(R.id.otherExcerpt);
this.articleUrl=(TextView)itemView.findViewById(R.id.otherUrl);
this.favImage = (ImageView) itemView.findViewById(R.id.imgbtn_favorite);
favImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String tag = favImage.getTag().toString();
if(!favImage.isSelected()) {
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(mContext, feedItemList.get(getItemCount() - 1));
// Toast.makeText(mContext, mContext.getResources().getString(R.string.add_favr),
// Toast.LENGTH_SHORT).show();
//SnackBack
SnackbarManager.show(
Snackbar.with(mContext)
.text(R.string.add_favr)
.textColor(Color.WHITE)
.color(Color.RED)
.duration(Snackbar.SnackbarDuration.LENGTH_SHORT));
//End of SnackBack
favImage.setTag("red");
favImage.setImageResource(R.drawable.heart_red);
}
}
else {
sharedPreference.removeFavorite(mContext, feedItemList.get(getItemCount() - 1));
favImage.setTag("grey");
favImage.setImageResource(R.drawable.heart_grey);
//SnackBack
SnackbarManager.show(
Snackbar.with(mContext)
.text(R.string.remove_favr)
.textColor(Color.WHITE)
.color(Color.RED) .duration(Snackbar.SnackbarDuration.LENGTH_SHORT).animation(false));
//End of SnackBack
}
}
}
}
I ran into this problem a couple of days ago - the reason is that you have not updated your feedItemList with the applicable changes. If you update the list by setting some of the member variables (like setExcerpt()) of the Latest class once it has change, your recyclerview will work properly.

Android ListView showing only first 4 items on repeat

I have a Fragment called User Management where I collect data from a server and display it in a ListView. It's also refreshable via SwipeRefreshLayout.
What happens is, if I get data on 1-4 users, it displays the data correctly. However, if I get data on more than 4 users, it displays the first 4 correctly, and instead of the fifth, it's the first one again, instead of the 6th, it's the second one and so on and so on.
I've tried everything I could think of, the adapter is getting the data correctly, the ListView is getting the adapter correctly, but for some reason, it peaks at 4 users displayed, and simply repeats them after that (the funny thing is, if I add a user and then refresh, it simply repeats the next user one more time in the list, so it's definitely aware of the change in user number)
Can you help me finding the problem?
The java class:
package com.softwarenation.jetfuel.fragments.userManagement;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.softwarenation.jetfuel.R;
import com.softwarenation.jetfuel.activities.MainActivity;
import com.softwarenation.jetfuel.fragments.Stations;
import com.softwarenation.jetfuel.managers.JetfuelManager;
import com.softwarenation.jetfuel.managers.StatusManager;
import com.softwarenation.jetfuel.managers.UserManager;
import com.softwarenation.jetfuel.utility.Global;
import com.softwarenation.jetfuel.utility.GlobalConnection;
import com.softwarenation.jetfuel.utility.users.User_pictures;
import com.softwarenation.jetfuel.utility.users.Users_mana;
import org.nicktate.projectile.Method;
import org.nicktate.projectile.Projectile;
import org.nicktate.projectile.StringListener;
import java.io.InputStream;
import java.util.ArrayList;
public class UserManagement extends Fragment {
private SwipeRefreshLayout swipeRefreshLayout;
//private View refreshView;
private Global font = new Global();
private ListView listView;
private ArrayList<User_pictures> pictureses = new ArrayList<User_pictures>();
private static boolean isfirst = false;
private PullToRefreshListView pullToRefreshView;
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**---------------------------------------------------------------------------------------------*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_usermanagemnet, container, false);
listView = (ListView)rootView.findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
// refreshView = (View) rootView.findViewById(R.id.swipe);
//First time, we get the data from a server, then only display that data until the user calls for a refresh
if(!StatusManager.getInstance().getUsermStatus()){
UsersTask usersTask = new UsersTask();
usersTask.execute();
}else{
setContent();
}
Button addUser = (Button)rootView.findViewById(R.id.addUser_button);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new AddUser();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
// Set a listener to be invoked when the list should be refreshed.
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.e("start","onRefresh");
new GetDataTask().execute();
}
}
);
/* pullToRefreshView = (PullToRefreshListView)rootView.findViewById(R.id.pull_to_refresh_listview);
pullToRefreshView.bringToFront();
pullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});*/
return rootView;
}
public void setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener){
swipeRefreshLayout.setOnRefreshListener(listener);
}
public boolean isRefreshing(){
return swipeRefreshLayout.isRefreshing();
}
public void setRefreshing(boolean refreshing){
swipeRefreshLayout.setRefreshing(refreshing);
}
public SwipeRefreshLayout getSwipeRefreshLayout(){
return swipeRefreshLayout;
}
//on refresh, get new data from the server
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... voids) {Log.e("start","GetDataTask");
UsersTask usersTask = new UsersTask();
usersTask.execute();
return new String[0];
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
// pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
MainActivity.setBackDisabled(false);
Log.e("GetDataTask","completed");
}
}
private class SampleItem {
public String id;
public String title;
public String username;
public String groupName;
public int userPicture;
public int editPicture;
public int dPicture;
public String activated;
public SampleItem(String id, String title, String username, String groupName, int userPicture, int editPicture, int dPicture, String activated ) {
this.id = id;
this.title = title;
this.username = username;
this.groupName = groupName;
this.userPicture = userPicture;
this.editPicture = editPicture;
this.dPicture = dPicture;
this.activated = activated;
}
}
static class ViewHolder {
private String checkBox;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private RelativeLayout relativeLayout2;
public void setCheckBox(String checkBox) {
this.checkBox = checkBox;
}
public void setLinearLayout(LinearLayout linearLayout) {
this.linearLayout = linearLayout;
}
public void setRelativeLayout(RelativeLayout relativeLayout) {
this.relativeLayout = relativeLayout;
}
public void setRelativeLayout2(RelativeLayout relativeLayout2) {
this.relativeLayout2 = relativeLayout2;
}
public LinearLayout getLinearLayout() {
return linearLayout;
}
public RelativeLayout getRelativeLayout() {
return relativeLayout;
}
public RelativeLayout getRelativeLayout2() {
return relativeLayout2;
}
public RelativeLayout getCheckBox() {
return relativeLayout;
}
}
public class SampleAdapter extends ArrayAdapter<SampleItem> {
final ViewHolder holder = new ViewHolder();
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
ImageView userPicture = (ImageView)convertView.findViewById(R.id.userpicture);
userPicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
TextView title = (TextView)convertView.findViewById(R.id.user_name);
font.setFont(title, 3, getActivity());
title.setText(getItem(position).title);
TextView username = (TextView)convertView.findViewById(R.id.username);
font.setFont(username, 2, getActivity());
username.setText(getItem(position).username);
TextView groupname = (TextView)convertView.findViewById(R.id.groupName);
font.setFont(groupname, 2, getActivity());
groupname.setText(getItem(position).groupName);
ImageView useredit = (ImageView)convertView.findViewById(R.id.editbutton);
useredit.setImageDrawable(getResources().getDrawable(getItem(position).editPicture));
useredit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new EditProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
/**---------------*/
ImageView userdelate = (ImageView)convertView.findViewById(R.id.deletebutton);
userdelate.setImageDrawable(getResources().getDrawable(getItem(position).dPicture));
holder.setLinearLayout((LinearLayout)convertView.findViewById(R.id.lin_show_profile));
//LinearLayout show = (LinearLayout)convertView.findViewById(R.id.lin_show_profile);
holder.getLinearLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new ShowProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
//
holder.setRelativeLayout((RelativeLayout)convertView.findViewById(R.id.delate_user));
//RelativeLayout delete_user = (RelativeLayout)convertView.findViewById(R.id.delate_user);
holder.getRelativeLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogStop("Are you sure?", getItem(position).username, getActivity(), getItem(position).id);
}
});
//
//holder.setCheckBox(getItem(position).activated);
//
/**---------------*/
//Red or Blue background
// RelativeLayout settings = (RelativeLayout)convertView.findViewById(R.id.settingsbutton);
holder.setRelativeLayout2((RelativeLayout) convertView.findViewById(R.id.settingsbutton));
//if(getItem(position).activated.equals("false")) {
if (getItem(position).activated.equals("false")) {
holder.getLinearLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout2().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
}
//holder.setCheckBox(getItem(position).activated);
convertView.setTag(holder);
} else {
convertView.getTag();
}
return convertView;
}
}
public void DialogStop(String title, String message,Context context, final String id){
new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dialog.cancel();
DeleteTask deleteTask = new DeleteTask();
deleteTask.execute(id);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private class DeleteTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
String response = null;
try {
response = new GlobalConnection().DELETE( getString(R.string.apicdeleteuser) + params[0].toString() );
Log.v("response", response + "");
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
Log.v("response", response + "");
}
}
private class UsersTask extends AsyncTask<String, Void, ArrayList<Users_mana>> {
#Override
protected ArrayList<Users_mana> doInBackground(String... strings) {
//Users_mana users = null;
String response = null;
ArrayList<Users_mana> users_manas = null;
try{Log.e("start","GET via GlobalConnection()");
response = new GlobalConnection().GET( getString(R.string.apiusers));
users_manas = new Gson().fromJson(response, new TypeToken<ArrayList<Users_mana>>(){}.getType());
Log.e("start","setUsers_mana");
UserManager.getInstance().setUsers_mana(users_manas);
}catch (Exception e){
Log.e("response error", e.getMessage().toString());
}
return users_manas;
}
#Override
protected void onPostExecute(ArrayList<Users_mana> response) {
if(!response.isEmpty()) {Log.e("start","setContent()");
setContent();
StatusManager.getInstance().setUsermStatus(true);
Log.e("UsermStatus:",String.valueOf(StatusManager.getInstance().getUsermStatus()));
}
super.onPostExecute(response);
}
}
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
/*
private class PicturesTask extends AsyncTask<String, String ,String>{
#Override
protected String doInBackground(String... urls) {
//String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
for(int i = 0; i < urls.length; i++) {
if(UserManager.getInstance().getUsers_mana().get(i).photo != null) {
InputStream in = new java.net.URL(getString(R.string.jetfuel_url ) + UserManager.getInstance().getUsers_mana().get(i).username).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
pictureses.add(new User_pictures(mIcon11, UserManager.getInstance().getUsers_mana().get(i).username, UserManager.getInstance().getUsers_mana().get(i).id));
UserManager.getInstance().setUserPictureses(pictureses);
}
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(!UserManager.getInstance().getUserPictureses().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUserPictureses().size(); i++) {
Log.v("pictures", UserManager.getInstance().getUserPictureses().get(i).picture + "");
}
}
super.onPostExecute(s);
}
}
*/
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
//menu.removeItem(R.id.Station);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Station:
Fragment fragment = new Stations();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**---------------------------------------------------------------------------------------------*/
}
The xml view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue">
<Button
android:id="#+id/addUser_button"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="#string/add_user"
android:background="#drawable/button_yellow_background"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#color/blue"/>
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
Thank you!
There is a huge problem in your SampleAdapter.getView() method.
When you scroll down the View disappearing at the top of the screen is reused to be injected at the bottom. This reused View is the convertView you get as getView parameter.
As you code is, the reused view is injected with the exact same data (because if (convertView == null) { is always false when you scroll).
Images and texts are not updated.
When you scroll down, the element disappearing at the top just appears at the bottom, and so does others...
You should be doing something like:
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
// The ViewHolder constructor should handle the mapping of its views
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here you should only use holder as in:
holder.userpicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
...
}
This method looks strange, and is perhaps suspect. I don't see getUsers_mana() defined anywhere in this sample code, so I don't know if it is the problem or not. For one, you should call that 'UserManager.getInstance().getUsers_mana()' and then 'get(i)' once each and store the results in variables.
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
It is because you are not doing anything in the
else {
convertView.getTag();
}
Check here
Why we should re-assign values for a recycled convertView in getView()
You have to reassign values to the convertView with the data of the 5th roq, 6th row etc. otherwise it still contains the old data
Remove the initialization of holder on the top and just put this line of code in the beginning of getView function.
ViewHolder holder = null;
You need to re initialize holder if its null and you need to update it with latest data if its not null.
See this sample it might help you
https://github.com/erikwt/PullToRefresh-ListView

Categories

Resources