-1

I used CustomListAdapter class which extends baseadapter. In that i have a button on each view of the list view ..when I lick on the button it should print a text. everything is working fine except that the text is printed in someother view too. I have found many similar question but no exact solution.

 public class CustomListAdapter extends BaseAdapter  {

List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;

  ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2;
ArrayList<String> listItems;

public int count1 = 0;
 ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email;
int i ;
ImageButton like;
ImageButton share;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
  private static String url_all_propertiesdel = IP+"/studio/getdelete_all_agent.php";

  boolean isSelected;
  int a,a1,b,b1;

    //private static final String TAG_SUCCESS1 = "mass";
    private static final String TAG_USER = "users";

    private static final String TAG_PRO = "properties";
    //private static final String TAG_PRO1 = "properties1";
    // products JSONArray
    JSONArray users = null;
    //JSONArray users1 = null;
     View view;

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
 SharedPreferences sPref;
// int position;


public CustomListAdapter(Context context, List<HashMap<String, Object>> models) {
    this.context = context;
    this. models = models;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.counters = new int[30];

    //this.session_email = sPref.getString("SESSION_UID","");

}

public class ViewHolder {

       public TextView countt;


       public ImageButton like,share;


    }

public void clear(){
    if(models!=null)
        models.clear();
}

@Override
public int getCount() {
    return models.size();
}

public HashMap<String, Object> getItem(int position) {
    return models.get(position);

}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return position;
} 

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return 1;
}

@Override
public View getView( int position, final View convertView,  ViewGroup parent) {
        //  view = null;
      view = convertView;

          ViewHolder viewHolder;

        pos = getItemViewType(position);
      //  long posn = getItemId(position);
     // final int paps= (int)posn ;
        if (view == null) {
            viewHolder = new ViewHolder();
            view = inflater.inflate(R.layout.fragment_home2, parent, false);
            //your code

            //add below code after (end of) your code
            viewHolder.like=(ImageButton)view.findViewById(R.id.likem);
            viewHolder.share=(ImageButton)view.findViewById(R.id.share);

            viewHolder.like.setTag(position);  
          //  viewHolder.share.setTag(position);

          /*  viewHolder.share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    HashMap<String, Object> item = models.get(position);
                            Intent share = new Intent(Intent.ACTION_SEND);

                            // If you want to share a png image only, you can do:
                            // setType("image/png"); OR for jpeg: setType("image/jpeg");
                            share.setType("image/*");

                            // Make sure you put example png image named myImage.png in your
                            // directory
                            String imagePath = Environment.getExternalStorageDirectory()
                                    + "/108.png";

                            String imagePath = (String)item.get("IMAGE");

                            Toast.makeText(context, imagePath, Toast.LENGTH_LONG).show();

                            File imageFileToShare = new File(imagePath);

                            Uri uri = Uri.fromFile(imageFileToShare);
                            share.putExtra(Intent.EXTRA_STREAM, uri);

                            context.startActivity(Intent.createChooser(share, "Share Image!"));



                }


            });*/


           // viewHolder.share.setOnItemClickListener(this);

            viewHolder.like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (Integer) v.getTag();
                   // viewHolder.countt = (TextView) v.findViewById(R.id.count);
                    HashMap<String, Object> item = models.get(position);
                    isSelected = (Boolean) item.get("selected");
                   item.put("selected", !isSelected);
                  notifyDataSetChanged();




                }
            });
        } else {
           viewHolder = (ViewHolder) view.getTag();
        }




     final HashMap<String, Object> item = getItem(position);



     // like = (ImageView) view.findViewById(R.id.like);
     //sharingButton = (ImageButton) view.findViewById(R.id.share);

  //   final HashMap<String, Object> item1 = getItem(position);
   isSelected = (Boolean) item.get("selected");

     if (isSelected) {

         viewHolder.like.setBackgroundResource(R.drawable.checked);
     } else {
         viewHolder.like.setBackgroundResource(R.drawable.unchecked);
     }


     pic = (ImageView) view.findViewById(R.id.profilePic);
     name = (TextView) view.findViewById(R.id.name);
     idas = (TextView) view.findViewById(R.id.hpid);
     idas2 = (TextView) view.findViewById(R.id.hpid2);
     timestamp = (TextView) view.findViewById(R.id.timestamp);
     msg = (TextView) view.findViewById(R.id.txtStatusMsg);
     url = (TextView) view.findViewById(R.id.txtUrl);
     image = (ImageView) view.findViewById(R.id.feedImage1);
     //countt =(TextView)view.findViewById(R.id.count);
     /*if any exception raises please use 
        locationTitle.setText(((String)item.get(“NAME�?)));
        use this technique for the Image also.
     */
     //holder.like.setText(item.get(item));
     //like.setText((String) item.get(R.id.like));
     idas.setText((CharSequence) item.get("UIDAS"));
    // listItems.add(idas.getText().toString());
     name.setText((CharSequence) item.get("NAME"));
     timestamp.setText((CharSequence) item.get("TIME"));
     msg.setText((CharSequence) item.get("MSG"));
     url.setText((CharSequence) item.get("URL"));









     //countt.setText((CharSequence) item.get("COUN"));
     //count.setText("" + count1);


     int w = image.getWidth();
     int h = image.getHeight();

     if (w > 1000)
     {
          a=w-1000;
          b=w-a;
     }

     else
     {
         b=w;
     }


     if (h > 1000)
     {
          a1=h-1000;
          b1=h-a1;
     }

     else
     {
         b1=h;
     }

        Picasso.with(context)
        //.load("PIC")
     .load((String)item.get("PIC"))
        .placeholder(R.drawable.profile_dummy)
        //.error(R.drawable.ic_whats_hot)
        .resize(50, 50)
    //          .centerCrop()
       // .fit()
        .into(pic);



        /*Display display = getActivity().getWindowManager().getDefaultDisplay(); 
        Point size = new Point();
        display.getSize(size); 
        int width = size.x;*/



     Picasso.with(context)
     .load((String)item.get("IMAGE"))

    //.load("IMAGE")
    // .placeholder(R.drawable.ic_pages)
     //.error(R.drawable.ic_home)
   .resize(1000,b1)
    .onlyScaleDown()
    //.centerCrop()
 // .fit().centerInside()
     .into(image);



     /*if ((image).length() < 0) 
        {   
            //image.setVisibility(View.VISIBLE);
            //  invalid = true;
         idas2.setText(1);
            // Toast.makeText(getApplicationContext(), "hgghghghjgh", Toast.LENGTH_LONG).show(); 

        }*/





    /* delam.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Integer index = (Integer) v.getTag();
                       // pacm = idas.getText().toString();

                        listItems.remove(index.intValue());  
                        notifyDataSetChanged();
                    }
                }

                 );
     */







     /*
     delam.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


            pacm = idas.getText().toString();
            removeItemFromList();   

        }


    });
                    */      



   /*  like.setTag(position);   

     like.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            //  int p = (Integer)v.getTag();
                //int p;
            //int posit=(Integer)v.getTag();
                //String s = view[position];
                //Context get = null;
                //Toast.makeText(context, String.valueOf(p)  , Toast.LENGTH_LONG).show();
                //like.setBackgroundResource(R.drawable.checked);

                if( viewHolder.like.isSelected()){
                     viewHolder.like.setSelected(false);
                    //ctv.setBackgroundColor (Color.parseColor("#ffffff"));
                     viewHolder.like.setBackgroundResource(R.drawable.unchecked);


                 }else if(! viewHolder.like.isSelected()){
                     viewHolder.like.setSelected(true);
                        //ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
                     viewHolder.like.setBackgroundResource(R.drawable.checked);



                   }

             }  


        });*/


     return view;
  }



 // HashMap<String, Object> item = models.get(position);





}   
Anish Yesudasan
  • 11
  • 1
  • 1
  • 8

2 Answers2

0

This problem is due to recycling of Viewholder object in your ListView through convertView. Do not make logic based on the view state as the same state can be passed to some another item of ListView, where it supposed to be presented. So what to do? Hold your state on your data Item. And use notify dataSetChanged when you click some item not change its background Directly.

You can see example here. That one id for RecyclerView Adapter, but concept is same. RecyclerView causes issue when recycling

Community
  • 1
  • 1
Mahendra Chhimwal
  • 1,810
  • 5
  • 21
  • 33
0

Well try this, in your HashMap list you need to have one more item called selected to store selected row status

@Override
public View getView(int position, final View convertView, ViewGroup parent) {
    //your code

    if (view == null) {
        viewHolder = new ViewHolder();
        //your code

        //add below code after (end of) your code
        viewHolder.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                HashMap<String, Object> item = models.get(position);
                boolean isSelected = (boolean) item.get("selected");
                item.put("selected", !isSelected);
                notifyDataSetChanged();
            }
        });
    } else {
        viewHolder = (ViewHolder) view.getTag();
    }

    //updated
    viewHolder.like.setTag(position);  

    final HashMap<String, Object> item = getItem(position);
    boolean isSelected = (boolean) item.get("selected");

    if (isSelected) {
        viewHolder.like.setBackgroundResource(R.drawable.checked);
    } else {
        viewHolder.like.setBackgroundResource(R.drawable.unchecked);
    }

    //your other code
}
Bharatesh
  • 8,943
  • 3
  • 38
  • 67