Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView Adapter Crash issue/Duplicates

I'm basically trying to display multiple views via the same ListView adapter. However, the adapter ends up generating multiple duplicates and crashes sometimes as well with a NullPointer. My guess is that I have implemented the adapter all wrong. Here's my complete code:

The item could either be a photo or a text.

Adapter:

 public class FeedAdapter extends BaseAdapter {

        static private Activity activity;
        private static LayoutInflater inflater = null;
        ArrayList<ActivityTable> actList = new ArrayList<ActivityTable>();
        Holder holder;

    public FeedAdapter(Activity a, ArrayList<ActivityTable> actList) {
            activity = a;
            this.actList = actList;
        }

    public View getView(int position, View convertView, ViewGroup parent) {

            Holder holder;

            final ActivityTable act = actList.get(position);
    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

     if (convertView == null) {

                if (act.getType().equals("text")) {

                    convertView = inflater.inflate(R.layout.feed_single_text, null);
                    holder = new Holder();

                    //More code that Set the caption to the holder
                    convertView.setTag(holder);

                }

                if (act.getType().equals("photo")) {

                    convertView = inflater.inflate(R.layout.feed_single_picture, parent, false);
                    holder = new Holder();
                    holder.media = (ImageView) convertView.findViewById(R.id.postphoto);
                    //More code that Set the photo to the holder
                    convertView.setTag(holder);
                }

            } else {

                holder = (Holder) convertView.getTag();

            }

         return convertView;
    }


    public static class Holder {
           ImageView media;
           TextView caption;
    }
}

Am I inflating multiple views in the same adapter the wrong way? Can anyone point out the error?

like image 824
Dinuka Jay Avatar asked Mar 26 '26 09:03

Dinuka Jay


1 Answers

You have 2 diffrent layout for each row so I think you should add

@Override
public int getViewTypeCount() {
    return 2;
}

to your listview adapter
In your code, try to initial your LayoutInflater inside the constructor of your adapter

public FeedAdapter(Activity a, ArrayList<ActivityTable> actList) {
    ...
    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}  

And also you should optimize your ListView performance

Here is my experience

like image 54
Linh Avatar answered Mar 27 '26 23:03

Linh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!