I have a list in a "listview" to scroll the list using this mess,
grouping and the list has a header with icons.
public class MyCustomAdapter extends BaseAdapter {
private static final String ASSETS_DIR = "images/";
private static final int TYPE_HEAD = -1;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private Context ctx;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context context) {
this.ctx = context;
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public void addHeadItem(){
mData.add("");
mSeparatorsSet.add(0);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
//return equipos.size();
}
#Override
public String getItem(int position) {
return mData.get(position) ;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemViewType(int position) {
if (position==0)
return TYPE_HEAD;
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView
+ " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.list_item, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
holder.textView2 = (TextView) convertView.findViewById(R.id.textView2);
holder.textView3 = (TextView) convertView.findViewById(R.id.textView3);
holder.imageView1 = (ImageView) convertView.findViewById(R.id.imageView1);
String[] datos = mData.get(position).split("-");
holder.textView1.setText(String.format(" %s - %s", datos[0],datos[1]));
holder.textView2.setText(datos[2]);
holder.textView3.setText(datos[3]);
String sel_bandera = datos[4].trim() ;
String imgFilePath = "";
if (sel_bandera.equals("verde")){
imgFilePath = ASSETS_DIR + "circle_green.png" ;
}else if (sel_bandera.equals("amarilla")){
imgFilePath = ASSETS_DIR + "circle_yellow.png";
}else {
imgFilePath = ASSETS_DIR + "circle_red.png";
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(this.ctx.getResources().getAssets().open(imgFilePath));
holder.imageView1.setImageBitmap(bitmap);
//bandera.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.list_group, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textSeparator);
holder.textView1.setText(mData.get(position));
break;
case TYPE_HEAD:
convertView = mInflater.inflate(R.layout.list_head, null);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
public static class ViewHolder {
public TextView textView1;
public TextView textView2;
public TextView textView3;
public ImageView imageView1;
public TextView getTextView1() {
return textView1;
}
public void setTextView1(TextView textView1) {
this.textView1 = textView1;
}
public TextView getTextView2() {
return textView2;
}
public void setTextView2(TextView textView2) {
this.textView2 = textView2;
}
public TextView getTextView3() {
return textView3;
}
public void setTextView3(TextView textView3) {
this.textView3 = textView3;
}
public ImageView getImageView1() {
return imageView1;
}
public void setImageView1(ImageView imageView1) {
this.imageView1 = imageView1;
}
}
}
public class EquiposActivity extends ListFragment implements OnTouchListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mAdapter = new MyCustomAdapter(getActivity());
if (lista.length > 0) {
String[] datos = lista[0].split("-");
cabecera_grupo = datos[4];
}
mAdapter.addHeadItem();
for (int i = 0; i < lista.length; i++) {
String[] datos = lista[i].split("-");
String grupo = datos[4];
if (i == 0) {
mAdapter.addSeparatorItem(grupo.replace("_", " "));
}
if (!grupo.equals(cabecera_grupo)) {
mAdapter.addSeparatorItem(grupo.replace("_", " "));
cabecera_grupo = grupo;
}
mAdapter.addItem(String.format("%s - %s - %s - %s - %s",
datos[0], datos[1], datos[2], datos[3], datos[5]));
}
setListAdapter(mAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
I suggest you to rewrite your getView() method, because I think that you are wrongly using ViewHolder pattern. Read this: http://www.jmanzano.es/blog/?p=166
Or just get rid of ViewHolder and code getView() without it.
Related
I have been trying to figure out how to make RecyclerView Adapter work with clickable images from a db. My app always crashes with the error "android.database.CursorIndexOutOfBoundsException: Index 4 requested, with a size of 4" when an image is clicked. When I add more items to the db, the index in the error increments as well. Please any help will be appreciated. See code snippets below.
`public class SelectItemRecycleViewAdapter extends RecyclerView.Adapter {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
PreferenceActivity.Header header;
Context context;
Cursor cursor;
RecyclerView.ViewHolder holder;
public SelectItemRecycleViewAdapter(Context mContext, Cursor mCursor, PreferenceActivity.Header header) {
context = mContext;
cursor = mCursor;
this.header = header;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.selection, parent, false);
if(viewType == TYPE_HEADER)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.add_item, parent, false);
return new VHHeader(v);
}
else if(viewType == TYPE_ITEM)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.display_items, parent, false);
return new VHItem(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
public Cursor swapCursor(Cursor mCursor) {
if (cursor == mCursor) {
return null;
}
Cursor oldCursor = cursor;
this.cursor = mCursor;
if (mCursor != null) {
this.notifyDataSetChanged();
}
return oldCursor;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder mHolder, int position) {
holder = mHolder;
if(holder instanceof VHHeader)
{
VHHeader VHheader = (VHHeader)holder;
VHheader.mAdd.setText( "ADD");
VHheader.mItem.setText( "ITEM");
}
else if(holder instanceof VHItem)
{
VHItem VHitem = (VHItem)holder;
int iPosition = position - 1;
cursor.moveToPosition(iPosition);
String iString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_IMAGE));
try {
byte[] bytarray = decode(String.valueOf(iString), Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
VHitem.mDisplayImage.setImageBitmap(bmimage);
} catch (Exception e){
}
String nString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_NAME));
VHitem.mDisplayName.setText(nString);
String pString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_PRICE));
VHitem.mDisplayPrice.setText(pString);
String bString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_BRAND));
if (bString.equals("")){
VHitem.mDisplayBrandView.setVisibility(View.GONE);
}
VHitem.mDisplayBrand.setText(bString);
String aString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_ATTRIBUTE));
if (aString.equals("")){
VHitem.mDisplayAttributeView.setVisibility(View.GONE);
} else {
VHitem.mDisplayAttribute.setText(aString);
}
String qString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_QUANTITY));
if (qString.equals("")){
VHitem.mDisplayQuantityView.setVisibility(View.GONE);
} else {
VHitem.mDisplayQuantity.setText( "Quantity - " + qString);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemPosition = holder.getAdapterPosition();
if(holder.getAdapterPosition() != RecyclerView.NO_POSITION){
cursor.move(itemPosition);
}
String bString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_BRAND));
String nString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_NAME));
String aString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_ATTRIBUTE));
String pString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_PRICE));
bString = bString + " ";
aString = " " + aString;
String description = bString + nString + aString;
String [] array = {description, pString};
mCallback.addArray(array);
}
});
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position)
{
return position == 0;
}
#Override
public int getItemCount() {
return (cursor == null) ? 0 : cursor.getCount() + 1;
}
class VHHeader extends RecyclerView.ViewHolder{
TextView mAdd;
TextView mItem;
public VHHeader(View itemView) {
super(itemView);
this.mAdd = (TextView) itemView.findViewById(R.id.add);
this.mItem = (TextView) itemView.findViewById(R.id.item);
}
}
class VHItem extends RecyclerView.ViewHolder{
ImageView mDisplayImage;
TextView mDisplayBrand;
TextView mDisplayName;
TextView mDisplayAttribute;
TextView mDisplayQuantity;
TextView mDisplayPrice;
View mDisplayImageView;
View mDisplayBrandView;
View mDisplayNameView;
View mDisplayAttributeView;
View mDisplayQuantityView;
View mDisplayPriceView;
View v;
public VHItem(View itemView) {
super(itemView);
this.mDisplayImage = (ImageView) itemView.findViewById(R.id.displayImage);
this.mDisplayBrand = (TextView) itemView.findViewById(R.id.displayBrand);
this.mDisplayName = (TextView) itemView.findViewById(R.id.displayName);
this.mDisplayAttribute = (TextView) itemView.findViewById(R.id.displayAttribute);
this.mDisplayQuantity = (TextView) itemView.findViewById(R.id.displayQuantity);
this.mDisplayPrice = (TextView) itemView.findViewById(R.id.displayPrice);
this.mDisplayImageView = itemView.findViewById(R.id.displayImageView);
this.mDisplayBrandView = itemView.findViewById(R.id.displayBrandView);
this.mDisplayNameView = itemView.findViewById(R.id.displayNameView);
this.mDisplayAttributeView = itemView.findViewById(R.id.displayAttributeView);
this.mDisplayQuantityView = itemView.findViewById(R.id.displayQuantityView);
this.mDisplayPriceView = itemView.findViewById(R.id.displayPriceView);
}
}
public interface Callback{
void addArray(String[] a);
}
private Callback mCallback;
public void setListener(Callback callBack){
mCallback=callBack;
`
Error is in below code, it always return plus 1 index, because you write cursor.getCount()+1:
#Override
public int getItemCount() {
return (cursor == null) ? 0 : cursor.getCount() + 1;
}
Replace code with:
#Override
public int getItemCount() {
return (cursor == null) ? 0 : cursor.getCount();
}
#Override
public int getItemCount() {
return (cursor.getCount());
}
After many days of struggle, I finally found a solution to my problem. See code below. Many thanks to #Caspain and #Asif.
public class SelectItemRecycleViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private final View.OnClickListener mOnClickListener = new MyOnClickListener();
RecyclerView recyclerView;
PreferenceActivity.Header header;
Context context;
Cursor cursor;
public SelectItemRecycleViewAdapter(Context mContext, Cursor mCursor, PreferenceActivity.Header header) {
context = mContext;
cursor = mCursor;
this.header = header;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.selection, parent, false);
recyclerView = (RecyclerView) view.findViewById(R.id.grid);
if(viewType == TYPE_HEADER)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.add_item, parent, false);
return new VHHeader(v);
}
else if(viewType == TYPE_ITEM)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.display_items, parent, false);
return new VHItem(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
public Cursor swapCursor(Cursor mCursor) {
if (cursor == mCursor) {
return null;
}
Cursor oldCursor = cursor;
this.cursor = mCursor;
if (mCursor != null) {
this.notifyDataSetChanged();
}
return oldCursor;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof VHHeader)
{
VHHeader VHheader = (VHHeader)holder;
VHheader.mAdd.setText( "ADD");
VHheader.mItem.setText( "ITEM");
}
else if(holder instanceof VHItem)
{
VHItem VHitem = (VHItem)holder;
cursor.moveToPosition(position - 1);
holder.itemView.setOnClickListener(mOnClickListener);
String iString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_IMAGE));
try {
byte[] bytarray = decode(String.valueOf(iString), Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
VHitem.mDisplayImage.setImageBitmap(bmimage);
} catch (Exception e){
}
String nString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_NAME));
VHitem.mDisplayName.setText(nString);
String pString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_PRICE));
VHitem.mDisplayPrice.setText(pString);
String bString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_BRAND));
if (bString.equals("")){
VHitem.mDisplayBrandView.setVisibility(View.GONE);
}
VHitem.mDisplayBrand.setText(bString);
String aString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_ATTRIBUTE));
if (aString.equals("")){
VHitem.mDisplayAttributeView.setVisibility(View.GONE);
} else {
VHitem.mDisplayAttribute.setText(aString);
}
String qString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_QUANTITY));
if (qString.equals("")){
VHitem.mDisplayQuantityView.setVisibility(View.GONE);
} else {
VHitem.mDisplayQuantity.setText( "Quantity - " + qString);
}
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position)
{
return position == 0;
}
#Override
public int getItemCount() {
return (cursor == null) ? 0 : cursor.getCount() + 1;
}
class VHHeader extends RecyclerView.ViewHolder{
TextView mAdd;
TextView mItem;
public VHHeader(View itemView) {
super(itemView);
this.mAdd = (TextView) itemView.findViewById(R.id.add);
this.mItem = (TextView) itemView.findViewById(R.id.item);
}
}
class VHItem extends RecyclerView.ViewHolder{
ImageView mDisplayImage;
TextView mDisplayBrand;
TextView mDisplayName;
TextView mDisplayAttribute;
TextView mDisplayQuantity;
TextView mDisplayPrice;
View mDisplayImageView;
View mDisplayBrandView;
View mDisplayNameView;
View mDisplayAttributeView;
View mDisplayQuantityView;
View mDisplayPriceView;
View v;
public VHItem(View itemView) {
super(itemView);
this.mDisplayImage = (ImageView) itemView.findViewById(R.id.displayImage);
this.mDisplayBrand = (TextView) itemView.findViewById(R.id.displayBrand);
this.mDisplayName = (TextView) itemView.findViewById(R.id.displayName);
this.mDisplayAttribute = (TextView) itemView.findViewById(R.id.displayAttribute);
this.mDisplayQuantity = (TextView) itemView.findViewById(R.id.displayQuantity);
this.mDisplayPrice = (TextView) itemView.findViewById(R.id.displayPrice);
this.mDisplayImageView = itemView.findViewById(R.id.displayImageView);
this.mDisplayBrandView = itemView.findViewById(R.id.displayBrandView);
this.mDisplayNameView = itemView.findViewById(R.id.displayNameView);
this.mDisplayAttributeView = itemView.findViewById(R.id.displayAttributeView);
this.mDisplayQuantityView = itemView.findViewById(R.id.displayQuantityView);
this.mDisplayPriceView = itemView.findViewById(R.id.displayPriceView);
}
}
public interface Callback{
void addArray(String[] a);
}
private Callback mCallback;
public void setListener(Callback callBack){
mCallback=callBack;
}
private class MyOnClickListener implements View.OnClickListener {
#Override
public void onClick(final View v) {
int itemPosition = recyclerView.getChildLayoutPosition(v) - 1;
cursor.moveToPosition(itemPosition);
String bString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_BRAND));
String nString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_NAME));
String aString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_ATTRIBUTE));
String pString = cursor.getString(cursor.getColumnIndex(FlexpayContract.StockEntry.COLUMN_ITEM_PRICE));
bString = bString + " ";
aString = " " + aString;
String description = bString + nString + aString;
String [] array = {description, pString};
mCallback.addArray(array);
}
}
}
Am using check boxes in listview and am able to get the selected values also but my problem is when select the first position checkbox, automatically selecting 7th positioned checkbox. what will be the problem and please suggest me how to resolve this problem.
public class TransactionAdapter extends BaseAdapter {
LayoutInflater inflator;
String veh_reg_no;
String fuel_qty, total_amt;
public TransactionAdapter(Context context) {
inflator = getLayoutInflater();
}
#Override
public int getCount() {
if (pso_transaction_list.size() != 0)
return pso_transaction_list.size();
return 0;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Viewholder holder;
if(convertView==null) {
convertView = inflator.inflate(R.layout.pso_transation_layout, parent, false);
holder=new Viewholder();
holder.vT_tl_regnumber = (TextView) convertView.findViewById(R.id.vT_psotl_regnumber);
holder.vT_tl_drivername = (TextView) convertView.findViewById(R.id.vT_psotl_drivername);
holder.vT_tl_quantity = (TextView) convertView.findViewById(R.id.vT_psotl_quantity);
holder.vT_tl_totalCost = (TextView) convertView.findViewById(R.id.vT_psotl_totalCost);
holder.vT_psotl_payment = (TextView) convertView.findViewById(R.id.vT_psotl_payment);
holder.vI_psotl_statusimg = (ImageView) convertView.findViewById(R.id.vI_psotl_statusimg);
holder.vI_pha_Next = (ImageView) convertView.findViewById(R.id.vI_pha_Next);
holder.vI_pha_select = (CheckBox) convertView.findViewById(R.id.vI_pha_select);
holder.vT_psotl_unit = (TextView) convertView.findViewById(R.id.vT_psotl_unit);
holder.vT_pha_rsr = (TextView) convertView.findViewById(R.id.vT_pha_rsr);
holder.vL_psotl_nextlayout = (LinearLayout) convertView.findViewById(R.id.vL_psotl_nextlayout);
holder.vL_psotl_checkboxlayout = (LinearLayout) convertView.findViewById(R.id.vL_psotl_checkboxlayout);
convertView.setTag(holder);
}else{
holder = (Viewholder) convertView.getTag();
holder.vI_pha_select.setOnCheckedChangeListener(null);
}
if (pso_transaction_list.get(position).getPaymentMode().getId() == 1 && pso_transaction_list.get(position).getWFStatus() == 7) {
String pmt_status = "C/A | RCVD ";
holder.vT_psotl_payment.setText(pmt_status);
} else if (pso_transaction_list.get(position).getPaymentMode().getId() == 1) {
holder.vT_psotl_payment.setText("C/A");
} else {
holder.vT_psotl_payment.setText("P/G");
}
if (pso_transaction_list.get(position).getFuelStations().getCountry() != null) {
String[] currency = Getlocationaddress_by_address.currency(pso_transaction_list.get(position).getFuelStations().getCountry(), PsomytransactionlistActivity.this);
holder.vT_pha_rsr.setText(" " + currency[0] + " ");
holder.vT_psotl_unit.setText(" " + currency[1]);
}
holder.vI_pha_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked{
if (isChecked) {
selected_list_payment.add(pso_transaction_list.get(position).getPaymentMode().getId() + "");
selected_list.add(pso_transaction_list.get(position).getId() + "");
selecteddetails.add(pso_transaction_list.get(position).getVehicleNo());
payment_status.add(pso_transaction_list.get(position).getWFStatus() + "");
} else {
selected_list.remove(pso_transaction_list.get(position).getId() + "");
selected_list_payment.remove(pso_transaction_list.get(position).getPaymentMode().getId() + "");
selecteddetails.remove(pso_transaction_list.get(position).getVehicleNo());
payment_status.remove(pso_transaction_list.get(position).getWFStatus() + "");
}
}
});
veh_reg_no = pso_transaction_list.get(position).getVehicleNo();
holder.vT_tl_regnumber.setText(veh_reg_no);
holder.vT_tl_drivername.setText(pso_transaction_list.get(position).getDriver().getName());
fuel_qty = " " + pso_transaction_list.get(position).getQuantity() + "";
holder.vT_tl_quantity.setText(fuel_qty);
total_amt = pso_transaction_list.get(position).getTotalPrice() + "";
holder.vT_tl_totalCost.setText(total_amt);
holder.vL_psotl_nextlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent trans_intent = new Intent(PsomytransactionlistActivity.this, Psotransactiondetails.class);
trans_intent.putExtra("trans_details_position", position);
startActivity(trans_intent);
}
});
return convertView;
}
}
public static class Viewholder{
public TextView vT_tl_regnumber, vT_tl_drivername, vT_tl_quantity, vT_tl_totalCost, vT_psotl_payment, vT_psotl_unit, vT_pha_rsr;
public ImageView vI_psotl_statusimg, vI_pha_Next;
public LinearLayout vL_psotl_nextlayout, vL_psotl_checkboxlayout;
public CheckBox vI_pha_select;
}
Try this way. this worked for me
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<ModelPooja> listData;
public CustomAdapter(Context mainActivity, List<ModelPooja> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getPOOJA_LISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(ModelPooja item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
For Recyclerview try this way
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
Add two functions into your "Adapter" class
Note: If you use RecycleView, just add getItemViewType(int position).
I am trying to create a listview with three different item types I have a code that works with two XML files
Here is the adapter code:
private class MyCustomAdapter extends ArrayAdapter<String> {
String hello;
private String place;
int image;
private String temp;
private String humidity;
private String windspeed;
private String condition;
private int imageTop;
private String time;
private static final int TYPE_WEATHER = 0;
private static final int TYPE_TIME = 1;
private static final int TYPE_TOP = 2;
private static final int TYPE_MAX_COUNT = 3 + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context context, int resource) {
super(context, resource);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addWeather(final String place,final int image , final String temp,final String humidity,final String windspeed,final String condition) {
mData.add(place);
this.place = place;
this.image = image;
this.temp = temp;
this.humidity = humidity;
this.windspeed = windspeed;
this.condition = condition;
notifyDataSetChanged();
}
public void addFavapp(final String helloworld){
mData.add(place);
this.hello = helloworld;
notifyDataSetChanged();
}
public void addItem(final String item) {
this.time = item;
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_WEATHER : TYPE_TIME;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_WEATHER:
convertView = mInflater.inflate(R.layout.weather_item, null);
//Handling xml file weather_item
break;
case TYPE_TIME:
convertView = mInflater.inflate(R.layout.time_card_item, null);
holder.textView = (TextView)convertView.findViewById(R.id.two);
holder.textView.setText(time);
break;
case TYPE_TOP:
convertView = mInflater.inflate(R.layout.top_card_item, null);
//Handling xml file top_card_item
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
public ImageView image;
public TextView txtTemp;
public ImageView imageView;
public TextView txthumidity;
public TextView txtWind;
public TextView txtCond;
}
I tried creating a method called "addFavapp" to add my third XML file but I couldn't get it to work.
Help please.
Got it fixed by replacing
return mSeparatorsSet.contains(position) ? TYPE_WEATHER : TYPE_TIME;
Inside the getItemViewType
To
return position;
I am using androidimageloader.com and get a good bit of flicker as images load into the list, much unlike the demo and apps that use it. I have the imageLoader in the application class, and don't get why it flickers. The images are Facebook profile pictures for users. What would be causing this? Here is my adapter:
public class FriendAdapter extends BaseAdapter {
private Typeface tf;
LayoutInflater inflater;
private String[] nameEvents;
private String[] urls;
private ArrayList<Friend> friends;
ImageManager imageManager;
ImageTagFactory imageTagFactory;
public FriendAdapter(Activity activity, ArrayList<Friend> friends) {
this.friends = friends;
setData(this.friends);
tf = Typeface.createFromAsset(activity.getAssets(),
"fonts/Roboto-Condensed.ttf");
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageManager = BuzzbabaApplication.getImageLoader();
imageTagFactory = new ImageTagFactory(activity, R.drawable.no_pic_icon);
}
public View getView(int position, View convertView, ViewGroup parent) {
FriendView fView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.friend_layout, null);
fView = new FriendView();
fView.name = (TextView) convertView.findViewById(R.id.friendName);
fView.name.setTypeface(tf);
fView.pic = (ImageView) convertView.findViewById(R.id.profilePic);
convertView.setTag(fView);
} else {
fView = (FriendView) convertView.getTag();
}
fView.name.setText(nameEvents[position]);
// HomeScreen.imageLoader.DisplayImage(urls[position], fView.pic);
((ImageView) fView.pic).setTag(imageTagFactory.build(urls[position]));
imageManager.getLoader().load(fView.pic);
return convertView;
}
public void setData(ArrayList<Friend> friends) {
nameEvents = new String[friends.size()];
urls = new String[friends.size()];
int index = 0;
for (Friend f : friends) {
String pos = f.getName();
int num = f.getNumEvents();
if (num == 1) {
pos = pos + "\n" + num + " event";
} else {
pos = pos + "\n" + num + " events";
}
nameEvents[index] = pos;
urls[index] = f.getPictureURL();
index++;
}
}
static class FriendView {
TextView name;
ImageView pic;
}
public int getCount() {
return friends.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
when we scroll down or up getview problem?
getview not called properly?
at background images are loading from respective url?
layout is different for sender and receiver..
public class NewReadMessageAdapter extends BaseAdapter {
private Context context;
private LayoutInflater vi;
public ImageLoader imageLoader;
private Typeface tf;
private class Image {
String pic_url = new String();
Bitmap thumb;
String messege = new String();
int id;
String time = new String();
String sender_name = new String();
public boolean sender_user;
}
private Image[] images;
ArrayList<Messages> messages = new ArrayList<Messages>();
private TextView txt_msg;
private TextView txt_name;
private TextView txt_time;
Button btn_loc;
private ImageView img;
private ArrayList<Messages> mData = new ArrayList<Messages>();
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
private static final int TYPE_RECEIVER = 0;
private static final int TYPE_SENDER = 1;
public NewReadMessageAdapter(Context context,
ReadMessagePostParser messageParser, String sender_id,
String reciever_id) {
this.context = context;
tf = Typeface.createFromAsset(context.getAssets(), "fonts/tahoma.ttf");
messages = messageParser.getMessages();
imageLoader = new ImageLoader(context.getApplicationContext());
images = new Image[messages.size()];
for (int i = 0, j = messages.size(); i < j; i++) {
images[i] = new Image();
images[i].messege = messages.get(i).getMessage_text();
images[i].time = messages.get(i).getTime();
if (messages.get(i).getMessage_from().equals("YES")) {
images[i].sender_name = messageParser.sender_name;
images[i].pic_url = messageParser.sender_pic_url;
images[i].sender_user = true;
images[i].id = Integer.parseInt(sender_id);
} else {
images[i].sender_user = false;
images[i].id = Integer.parseInt(reciever_id);
images[i].sender_name = messageParser.reciever_name;
images[i].pic_url = messageParser.receiver_pic_url;
}
}
for (int i = 0; i < images.length; i++) {
System.out.println(images[i].pic_url + " " + images[i].sender_name
+ " " + images[i].messege);
}
vi = LayoutInflater.from(context);
imageLoader = new ImageLoader(context.getApplicationContext());
}
public void addItem(final Messages item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final Messages item) {
mData.add(item);
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SENDER : TYPE_RECEIVER;
}
#Override
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
switch (type) {
case TYPE_SENDER:
System.out.println("Sender");
holder = new ViewHolder();
convertView = vi.inflate(R.layout.list_row_layout_sender, null);
holder.txt_msg = (TextView) convertView
.findViewById(R.id.txt_msg);
holder.txt_name = (TextView) convertView
.findViewById(R.id.txt_name);
holder.txt_time = (TextView) convertView
.findViewById(R.id.txt_time);
holder.img = (ImageView) convertView
.findViewById(R.id.user_img);
holder.btn_loc = (Button) convertView
.findViewById(R.id.btn_loc);
convertView.setTag(holder);
break;
case TYPE_RECEIVER:
System.out.println("Receiver");
convertView = vi.inflate(R.layout.list_row_layout_receiver, null);
holder = new ViewHolder();
holder.txt_msg = (TextView) convertView
.findViewById(R.id.txt_msg);
holder.txt_name = (TextView) convertView
.findViewById(R.id.txt_name);
holder.txt_time = (TextView) convertView
.findViewById(R.id.txt_time);
holder.img = (ImageView) convertView
.findViewById(R.id.user_img);
holder.btn_loc = (Button) convertView
.findViewById(R.id.btn_loc);
convertView.setTag(holder);
break;
}
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.btn_loc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out
.println("-------------- btn_loc ------------------- Sender");
Developer.callIntent_userlocation(context, "18.50929796 ",
"73.79045371");
}
});
holder.txt_name.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("----Name----");
}
});
holder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("----Image----");
}
});
holder.txt_name.setText(mData.get(position).message_from);
holder.txt_time.setText(mData.get(position).time);
holder.txt_msg.setText(mData.get(position).message_text);
if (position != 0) {
cached = images[position - 1];
if (cached.sender_user == flag) {
holder.img.setVisibility(ImageView.INVISIBLE);
holder.txt_name.setVisibility(TextView.INVISIBLE);
} else
imageLoader.DisplayImage(images[position].pic_url.trim()
.replace(" ", "%20"), ReadMessageActivityNew.activity,
holder.img);
} else
imageLoader.DisplayImage(
images[position].pic_url.trim().replace(" ", "%20"),
ReadMessageActivityNew.activity, holder.img);
return convertView;
}
static class ViewHolder {
TextView txt_msg;
TextView txt_name;
TextView txt_time;
ImageView img;
Button btn_loc;
}
}
It is better to reuse convertView only when both the layouts are the same. As the layouts are different here, when you reuse a convertView used by sender for receiver, then the view may not be as expected.