Java.lang.IllegalArgumentException: cannot be viewTypeCount <1

I get this error:

 java.lang.IllegalArgumentException: Can't have a viewTypeCount < 1 

I am sure that I know for sure what causes it, but I do not know how to fix it.

My application loads user friends from the database. When a user has at least 1 friend to put him on the list, this is normal. When the user is brand new and has no friends yet, the application crashes due to the fact that the list has a counter of 0.

Is this just a case of error handling?

If I do not post all the necessary code, please let me know!

Here is my adapter:

 public class MyAdapter extends ArrayAdapter<HashMap<String, String>> { Context context; int resourceId; LayoutInflater inflater; private Context mContext; @Override public int getViewTypeCount() { return getCount(); } @Override public int getItemViewType(int position) { return position; } ArrayList<HashMap<String, String>> items; public MyAdapter (Context context, int resourceId, ArrayList<HashMap<String, String>> items) { super(context, resourceId, items); mContext = context; this.items =items; inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent){ final ViewHolder holder; if (convertView == null){ convertView = inflater.inflate(R.layout.list_item, null); holder = new ViewHolder(); holder.fbphoto = (ImageView)convertView.findViewById(R.id.fbphoto); holder.name = (TextView)convertView.findViewById(R.id.name); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } final HashMap<String,String> item = (HashMap<String,String> ) items.get(position); if (item != null) { String facebookProfilePicUrl = "https://graph.facebook.com/"+item.get(TAG_FACEBOOKID)+"/picture?width=150&height=150"; Picasso.with(mContext) .load(facebookProfilePicUrl) .placeholder(R.drawable.no_image) .into(holder.fbphoto); holder.name.setText(item.get(TAG_USERNAME)); } return convertView; } public class ViewHolder { ImageView fbphoto; TextView name; } } 
+6
source share
3 answers

I think you missed the point of ViewTypeCount. You must return the number of different views in your list. This is important for reusing Views within the List.

You have 2 types of lists, one with a white background and one with a black background. When you return 2 as a ViewTypeCount, Listview knows that there are 2 types of Listitems and will not mix them in viewView.

so just use:

  public int getViewTypeCount() { return 1; } 

or do not override this method at all.

+21
source

getViewTypeCount returns the number of different views that this adapter can return. Since you are returning only one view, this should just return 1.

+2
source

Use this

 @Override public int getViewTypeCount() { if(getCount() > 0){ return getCount(); }else{ return super.getViewTypeCount(); } 

}

0
source

Source: https://habr.com/ru/post/972539/


All Articles