ListView Not updating properly afte using notifyDataSetChanged() - android

In adapter class i am trying to update 2 TextView after click event ,
holder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int qty = Integer.parseInt(holder.itemQuantity.getText().toString());
qty += 1;
holder.itemQuantity.setText(String.valueOf(qty));
holder.totalItemPrice.setText(String.valueOf(getTotal(position))+" ৳");
updateCartItemQuantity(position,holder.itemQuantity);
}
});
if i don't use notifyDataSetChanged(), first TextView change but not the second, but after using notifyDataSetChanged() that also stops. I am using BaseAdapter here.
adapter:
public class CartAdapter extends BaseAdapter {
private CartDatabaseSource cartDatabaseSource;
private Context context;
private ArrayList<CartModel> cartmodels;
private ShowCartItemsActivity showCartItemsActivity;
public CartAdapter(Context context, ArrayList<CartModel> cartmodels) {
cartDatabaseSource = new CartDatabaseSource(context);
this.context = context;
this.cartmodels = cartmodels;
this.showCartItemsActivity = (ShowCartItemsActivity) context;
}
private static class ViewHolder {
TextView itemName;
TextView itemPrice;
TextView itemQuantity;
TextView totalItemPrice;
TextView increase;
TextView decrease;
ImageView foodImage;
ImageView delete;
ImageView update;
}
#Override
public int getCount() {
return cartmodels.size();
}
#Override
public Object getItem(int position) {
return cartmodels.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_single_row,parent,false);
holder=new ViewHolder();
holder.itemName = (TextView) convertView.findViewById(R.id.cartItemName);
holder.itemPrice = (TextView) convertView.findViewById(R.id.cartItemPriceValue);
holder.itemQuantity = (TextView) convertView.findViewById(R.id.cartItemQuantityValue);
holder.totalItemPrice = (TextView) convertView.findViewById(R.id.cartItemTotalPriceValue);
holder.increase = (TextView) convertView.findViewById(R.id.increaseQuantity);
holder.decrease = (TextView) convertView.findViewById(R.id.decreaseQuantity);
holder.foodImage = (ImageView) convertView.findViewById(R.id.cartFoodImage);
holder.delete = (ImageView) convertView.findViewById(R.id.itemDeleteBtn);
holder.update = (ImageView) convertView.findViewById(R.id.updateQuantity);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Picasso.with(context).load(cartmodels.get(position).getFoodImage()).into(holder.foodImage);
holder.itemName.setText(cartmodels.get(position).getFoodName());
holder.itemPrice.setText(String.valueOf(cartmodels.get(position).getFoodPrice())+" ৳");
holder.itemQuantity.setText(String.valueOf(cartmodels.get(position).getFoodQty()));
holder.totalItemPrice.setText(String.valueOf(getTotal(position))+" ৳");
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = cartmodels.get(position).getCartID();
final boolean status = cartDatabaseSource.deleteItem(id);
if(status){
context.startActivity(new Intent(context, ShowCartItemsActivity.class));
Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "couldn't delete", Toast.LENGTH_SHORT).show();
}
}
});
holder.update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = cartmodels.get(position).getCartID();
int qty = Integer.parseInt(holder.itemQuantity.getText().toString());
final boolean status = cartDatabaseSource.updateCartItem(id,qty);
if(status){
context.startActivity(new Intent(context, ShowCartItemsActivity.class));
Toast.makeText(context, "updated", Toast.LENGTH_SHORT).show();
holder.update.setVisibility(View.GONE);
}else{
Toast.makeText(context, "couldn't update", Toast.LENGTH_SHORT).show();
}
}
});
holder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int qty = Integer.parseInt(holder.itemQuantity.getText().toString());
qty += 1;
holder.totalItemPrice.setText(String.valueOf(getTotal(position))+" ৳");
holder.itemQuantity.setText(String.valueOf(qty));
updateCartItemQuantity(position,holder.itemQuantity);
}
});
holder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int qty = Integer.parseInt(holder.itemQuantity.getText().toString());
if(qty > 1){
qty -= 1;
holder.itemQuantity.setText(String.valueOf(qty));
holder.totalItemPrice.setText(String.valueOf(getTotal(position))+" ৳");
updateCartItemQuantity(position,holder.itemQuantity);
}
}
});
return convertView;
}
private void updateCartItemQuantity(int position,TextView itemQuantity){
//notifyDataSetChanged();
int id = cartmodels.get(position).getCartID();
int qty = Integer.parseInt(itemQuantity.getText().toString());
final boolean status = cartDatabaseSource.updateCartItem(id,qty);
if(status){
if(context instanceof ShowCartItemsActivity){
//((ShowCartItemsActivity)context).setTotalPrice();
}
}else{
Toast.makeText(context, "couldn't update", Toast.LENGTH_SHORT).show();
}
}
private double getTotal(int position) {
int qty = cartmodels.get(position).getFoodQty();
double price = cartmodels.get(position).getFoodPrice();
return Math.round(price * qty);
}
}

Instead of notifyDataSetChanged() you should use notifyItemChanged(position) this way you don't need to rebind all your views.
But you shouldn't need to use this if you are setting OnClickListener inside your onBindViewHolder.

Remove all code from onClick method and put this code:
cartmodels.get(position).setFoodQty(cartmodels.get(position).getFoodQty()+1);
notifyDataSetChanged();

Related

Iterate quantity for items , custom adapter

I have a listview where every items have one TextView and 2 Buttons ( + and - ). I want to iterate the quantity from TextView when I press the + Button. After this, I need to sum up all items (price * item quantity) for every item from the list and put the result into new TextView(total cost). That is my adapter and activity main. I appreciate any help.
public class cartItemsAdapter extends BaseAdapter {
private ArrayList<items> itemsList;
private Context context;
public cartItemsAdapter(ArrayList<items> list,Context cont){
this.itemsList = list;
this.context=cont;
}
#Override
public int getCount() {
return this.itemsList.size();
}
#Override
public Object getItem(int position) {
return this.itemsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView==null){
LayoutInflater inf = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.list_cart_item_view,null);
holder = new ViewHolder();
holder.imageView = (ImageView)convertView.findViewById(R.id.icon_item);
holder.nameView = (TextView) convertView.findViewById(R.id.name_item);
holder.priceView=(TextView)convertView.findViewById(R.id.price_item);
holder.plusButton = (Button) convertView.findViewById(R.id.cart_plus_button);
holder.minusButton = (Button) convertView.findViewById(R.id.cart_minus_button);
holder.removeButton = (Button) convertView.findViewById(R.id.cart_remove_button);
holder.quantityView = (TextView) convertView.findViewById(R.id.cart_quantity_view);
convertView.setTag(holder);
}else{
holder=(ViewHolder)convertView.getTag();
}
items itm = itemsList.get(position);
holder.imageView.setImageResource(itm.getlImageId());
holder.nameView.setText(itm.getlName());
holder.priceView.setText(itm.getlPrice() + " $");
holder.quantityView.setText("1");
/*holder.plusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pquant=Integer.valueOf(quant.toString());
pquant++;
}
});
holder.minusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mquant=Integer.valueOf(quant.toString());
mquant--;
}
});*/
return convertView;
}
private static class ViewHolder{
public ImageView imageView;
public TextView nameView;
public TextView priceView;
public Button plusButton;
public Button minusButton;
public Button removeButton;
public TextView quantityView;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart);
plusBtn = findViewById(R.id.cart_plus_button);
minusBtn = findViewById(R.id.cart_minus_button);
removeBtn = findViewById(R.id.cart_remove_button);
quantity = findViewById(R.id.cart_quantity_view);
listView = (ListView) findViewById(R.id.cart_category_listview);
favoriteDbHelper = new DatabaseHelper(this);
item = favoriteDbHelper.getAllDataCart();
myAdapter = new cartItemsAdapter(item, this);
listView.setAdapter(myAdapter);
}
Actually this code of yours is pretty close:
holder.plusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pquant=Integer.valueOf(quant.toString());
pquant++;
}
});
holder.minusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mquant=Integer.valueOf(quant.toString());
mquant--;
}
});
All you need to do is to access itemsList inside onClick(View v). To make it simple, try this:
holder.plusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Items item = itemsList.get(position);
//now you can get your quant by accessing this item object
}
});
The key is to get current position using getAdapterPosition().

ListView Item's position repeated

I am creating a dynamic listview using fragment in which item's position are repeating after 6th index(Note- items are not repeating).
I have to change quantity of item on button click, but when I try to click and change quantity at index 0 it also changes the 7th index quantity.
Please help me out
Thanx in advance.
public class MenuListAdapter extends ArrayAdapter<DataModel> {
private Activity activity;
public String[] ItemsList = new String[1000];
public String[] ItemsRelPrice;
ArrayList<String> foodItemTitle = new ArrayList<>();
private static String currentTitle;
private String selection;
private String ttl;
public MenuListAdapter(Activity activity, int resource, List<DataModel> dataModelList) {
super(activity, resource, dataModelList);
this.activity = activity;
}
#Nullable
#Override
public DataModel getItem(int position) {
return super.getItem(position);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.food_item_list, parent, false);
holder = new ViewHolder(convertView);
final ImageButton addBtn = convertView.findViewById(R.id.img_add);
final ImageButton removeBtn = convertView.findViewById(R.id.img_remove);
final TextView qty = convertView.findViewById(R.id.item_quantity);
final TextView priceTtl = convertView.findViewById(R.id.txt_cost);
final TextView foodItem = convertView.findViewById(R.id.item_name);
final TextView foodPrice = convertView.findViewById(R.id.per_item_cost);
addBtn.setTag(position);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("btn tag", String.valueOf(addBtn.getTag()));
Log.v("qty tag", String.valueOf(qty.getTag()));
Log.v("Price tag", String.valueOf(priceTtl.getTag()));
int curntQty = Integer.parseInt(qty.getText().toString()) + 1;
int costPerItem = Integer.valueOf(foodPrice.getText().toString());
if (qty.getTag() == addBtn.getTag())
qty.setText(String.valueOf(curntQty));
if (priceTtl.getTag() == addBtn.getTag())
priceTtl.setText(String.valueOf(costPerItem * curntQty));
new MenuPage().addItem(costPerItem);
}
});
removeBtn.setTag(position);
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (qty.getText().toString() != "0") {
int qtyTtl = Integer.parseInt(qty.getText().toString()) - 1;
qty.setText(String.valueOf(qtyTtl));
int costPerItem = Integer.valueOf(foodPrice.getText().toString());
int curPrice = Integer.valueOf(priceTtl.getText().toString());
priceTtl.setText(String.valueOf(curPrice - costPerItem));
new MenuPage().removeItem(costPerItem);
} else {
Toast.makeText(getContext(), "Add Item First", Toast.LENGTH_SHORT).show();
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DataModel dataModel = getItem(position);
holder.foodItem.setTag(position);
holder.foodItem.setText(dataModel.getItemTitleFinal());
holder.foodPrice.setTag(position);
holder.foodPrice.setText(dataModel.getItemPriceFinal());
holder.foodType.setTag(position);
holder.foodType.setImageResource(dataModel.getItemImgFinal());
holder.addBtn.setTag(position);
holder.removeBtn.setTag(position);
holder.qty.setTag(position);
holder.priceCurnt.setTag(position);
return convertView;
}
private static class ViewHolder {
private TextView foodItem;
private TextView foodPrice;
private ImageView foodType;
private ImageButton addBtn;
private ImageButton removeBtn;
private TextView qty;
private TextView priceCurnt;
public ViewHolder(View v) {
foodItem = v.findViewById(R.id.item_name);
foodPrice = v.findViewById(R.id.per_item_cost);
foodType = v.findViewById(R.id.fdTypeImg);
addBtn = v.findViewById(R.id.img_add);
removeBtn = v.findViewById(R.id.img_remove);
qty = v.findViewById(R.id.item_quantity);
priceCurnt = v.findViewById(R.id.txt_cost);
}
}
}
I modified your adapter class. You need to have dataModelList which will act as source to inflate the view holders. Now, you need to supply the list through the constructor and make small modifications at places where I might have missed. Let me know if modifications are needed.
public class MenuListAdapter extends ArrayAdapter<DataModel> {
private Activity activity;
public String[] ItemsList = new String[1000];
public String[] ItemsRelPrice;
ArrayList<String> foodItemTitle = new ArrayList<>();
private static String currentTitle;
private String selection;
private String ttl;
//List of DataModel objects to inflate into view holders
private List<DataModel> dataModelList;
public MenuListAdapter(Activity activity, int resource, List<DataModel> dataModelList) {
super(activity, resource, dataModelList);
this.activity = activity;
//set the list in constructor
this.dataModelList = dataModelList;
}
#Nullable
#Override
public DataModel getItem(int position) {
return dataModelList.get(position);
}
#Override
public int getCount() {
return dataModelList.size();
}
#Override
public long getItemId(int position) {
return dataModelList.get(position).getId();
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.food_item_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//findViewById codes removed because they are unnecessary
//Copy to final object so that it can be used inside inner classes
final ViewHolder finalHolder = holder;
DataModel dataModel = getItem(position);
finalHolder.foodItem.setTag(position);
finalHolder.foodItem.setText(dataModel.getItemTitleFinal());
finalHolder.foodPrice.setTag(position);
finalHolder.foodPrice.setText(dataModel.getItemPriceFinal());
finalHolder.foodType.setTag(position);
finalHolder.foodType.setImageResource(dataModel.getItemImgFinal());
finalHolder.addBtn.setTag(position);
finalHolder.removeBtn.setTag(position);
finalHolder.qty.setTag(position);
finalHolder.priceCurnt.setTag(position);
finalHolder.addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("btn tag", String.valueOf(finalHolder.addBtn.getTag()));
Log.v("qty tag", String.valueOf(finalHolder.qty.getTag()));
Log.v("Price tag", String.valueOf(finalHolder.priceCurnt.getTag()));
int curntQty = Integer.parseInt(finalHolder.qty.getText().toString()) + 1;
int costPerItem = Integer.valueOf(finalHolder.foodPrice.getText().toString());
if (finalHolder.qty.getTag() == finalHolder.addBtn.getTag())
finalHolder.qty.setText(String.valueOf(curntQty));
if (finalHolder.priceCurnt.getTag() == finalHolder.addBtn.getTag())
finalHolder.priceCurnt.setText(String.valueOf(costPerItem * curntQty));
new MenuPage().addItem(costPerItem);
}
});
finalHolder.removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (finalHolder.qty.getText().toString() != "0") {
int qtyTtl = Integer.parseInt(finalHolder.qty.getText().toString()) - 1;
finalHolder.qty.setText(String.valueOf(qtyTtl));
int costPerItem = Integer.valueOf(finalHolder.foodPrice.getText().toString());
int curPrice = Integer.valueOf(finalHolder.priceCurnt.getText().toString());
finalHolder.priceCurnt.setText(String.valueOf(curPrice - costPerItem));
new MenuPage().removeItem(costPerItem);
} else {
Toast.makeText(getContext(), "Add Item First", Toast.LENGTH_SHORT).show();
}
}
});
return convertView;
}
private static class ViewHolder {
private TextView foodItem;
private TextView foodPrice;
private ImageView foodType;
private ImageButton addBtn;
private ImageButton removeBtn;
private TextView qty;
private TextView priceCurnt;
public ViewHolder(View v) {
foodItem = v.findViewById(R.id.item_name);
foodPrice = v.findViewById(R.id.per_item_cost);
foodType = v.findViewById(R.id.fdTypeImg);
addBtn = v.findViewById(R.id.img_add);
removeBtn = v.findViewById(R.id.img_remove);
qty = v.findViewById(R.id.item_quantity);
priceCurnt = v.findViewById(R.id.txt_cost);
}
}
}
Change your code addBtn.setOnClickListener to and do the same with removeBtn button.setOnClickListener
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("btn tag", String.valueOf(addBtn.getTag()));
Log.v("qty tag", String.valueOf(qty.getTag()));
Log.v("Price tag", String.valueOf(priceTtl.getTag()));
int curntQty = Integer.parseInt(qty.getText().toString()) + 1;
// update your quantity to data model here
dataModel.updateQuantiy(curntQty);
int costPerItem = Integer.valueOf(foodPrice.getText().toString());
/*if (qty.getTag() == addBtn.getTag())
qty.setText(String.valueOf(curntQty));*/
if (priceTtl.getTag() == addBtn.getTag())
priceTtl.setText(String.valueOf(costPerItem * curntQty));
new MenuPage().addItem(costPerItem);
// Notify that the data set change at the position to re-binding layout.
notifyItemChanged(position);
}
});
And
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// Your normal code
DataModel dataModel = getItem(position);
holder.foodItem.setTag(position);
holder.foodItem.setText(dataModel.getItemTitleFinal());
holder.foodPrice.setTag(position);
holder.foodPrice.setText(dataModel.getItemPriceFinal());
holder.foodType.setTag(position);
holder.foodType.setImageResource(dataModel.getItemImgFinal());
holder.addBtn.setTag(position);
holder.removeBtn.setTag(position);
holder.qty.setTag(position);
holder.priceCurnt.setTag(position);
// add your quantity to textview
holder.qty.setText(dataModel.getQuantity());
return convertView;
}
Change following code:
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.food_item_list, parent, false);
holder = new ViewHolder(convertView);
final ImageButton addBtn = convertView.findViewById(R.id.img_add);
final ImageButton removeBtn = convertView.findViewById(R.id.img_remove);
final TextView qty = convertView.findViewById(R.id.item_quantity);
final TextView priceTtl = convertView.findViewById(R.id.txt_cost);
final TextView foodItem = convertView.findViewById(R.id.item_name);
final TextView foodPrice = convertView.findViewById(R.id.per_item_cost);
addBtn.setTag(position);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("btn tag", String.valueOf(addBtn.getTag()));
Log.v("qty tag", String.valueOf(qty.getTag()));
Log.v("Price tag", String.valueOf(priceTtl.getTag()));
int curntQty = Integer.parseInt(qty.getText().toString()) + 1;
int costPerItem = Integer.valueOf(foodPrice.getText().toString());
if (qty.getTag() == addBtn.getTag())
qty.setText(String.valueOf(curntQty));
if (priceTtl.getTag() == addBtn.getTag())
priceTtl.setText(String.valueOf(costPerItem * curntQty));
new MenuPage().addItem(costPerItem);
}
});
removeBtn.setTag(position);
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (qty.getText().toString() != "0") {
int qtyTtl = Integer.parseInt(qty.getText().toString()) - 1;
qty.setText(String.valueOf(qtyTtl));
int costPerItem = Integer.valueOf(foodPrice.getText().toString());
int curPrice = Integer.valueOf(priceTtl.getText().toString());
priceTtl.setText(String.valueOf(curPrice - costPerItem));
new MenuPage().removeItem(costPerItem);
} else {
Toast.makeText(getContext(), "Add Item First", Toast.LENGTH_SHORT).show();
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DataModel dataModel = getItem(position);
holder.foodItem.setTag(position);
holder.foodItem.setText(dataModel.getItemTitleFinal());
holder.foodPrice.setTag(position);
holder.foodPrice.setText(dataModel.getItemPriceFinal());
holder.foodType.setTag(position);
holder.foodType.setImageResource(dataModel.getItemImgFinal());
holder.addBtn.setTag(position);
holder.removeBtn.setTag(position);
holder.qty.setTag(position);
holder.priceCurnt.setTag(position);
return convertView;
}
private static class ViewHolder {
private TextView foodItem;
private TextView foodPrice;
private ImageView foodType;
private ImageButton addBtn;
private ImageButton removeBtn;
private TextView qty;
private TextView priceCurnt;
public ViewHolder(View v) {
foodItem = v.findViewById(R.id.item_name);
foodPrice = v.findViewById(R.id.per_item_cost);
foodType = v.findViewById(R.id.fdTypeImg);
addBtn = v.findViewById(R.id.img_add);
removeBtn = v.findViewById(R.id.img_remove);
qty = v.findViewById(R.id.item_quantity);
priceCurnt = v.findViewById(R.id.txt_cost);
}
}
To:
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_stock, parent, false);
convertView = inflater.inflate(R.layout.food_item_list, parent, false);
holder = new ViewHolder(convertView);
final ImageButton addBtn = convertView.findViewById(R.id.img_add);
final ImageButton removeBtn = convertView.findViewById(R.id.img_remove);
final TextView qty = convertView.findViewById(R.id.item_quantity);
final TextView priceTtl = convertView.findViewById(R.id.txt_cost);
final TextView foodItem = convertView.findViewById(R.id.item_name);
final TextView foodPrice = convertView.findViewById(R.id.per_item_cost);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DataModel dataModel = getItem(position);
holder.foodItem.setTag(position);
holder.foodItem.setText(dataModel.getItemTitleFinal());
holder.foodPrice.setTag(position);
holder.foodPrice.setText(dataModel.getItemPriceFinal());
holder.foodType.setTag(position);
holder.foodType.setImageResource(dataModel.getItemImgFinal());
holder.addBtn.setTag(position);
holder.removeBtn.setTag(position);
holder.qty.setTag(position);
holder.priceCurnt.setTag(position);
holder.addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("btn tag", String.valueOf(addBtn.getTag()));
Log.v("qty tag", String.valueOf(qty.getTag()));
Log.v("Price tag", String.valueOf(priceTtl.getTag()));
int curntQty = Integer.parseInt(qty.getText().toString()) + 1;
int costPerItem = Integer.valueOf(foodPrice.getText().toString());
if (qty.getTag() == addBtn.getTag())
qty.setText(String.valueOf(curntQty));
if (priceTtl.getTag() == addBtn.getTag())
priceTtl.setText(String.valueOf(costPerItem * curntQty));
new MenuPage().addItem(costPerItem);
}
});
holder.removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (qty.getText().toString() != "0") {
int qtyTtl = Integer.parseInt(qty.getText().toString()) - 1;
qty.setText(String.valueOf(qtyTtl));
int costPerItem = Integer.valueOf(foodPrice.getText().toString());
int curPrice = Integer.valueOf(priceTtl.getText().toString());
priceTtl.setText(String.valueOf(curPrice - costPerItem));
new MenuPage().removeItem(costPerItem);
} else {
Toast.makeText(getContext(), "Add Item First", Toast.LENGTH_SHORT).show();
}
}
});
return convertView;
}
private static class ViewHolder {
private TextView foodItem;
private TextView foodPrice;
private ImageView foodType;
private ImageButton addBtn;
private ImageButton removeBtn;
private TextView qty;
private TextView priceCurnt;
public ViewHolder(View v) {
foodItem = v.findViewById(R.id.item_name);
foodPrice = v.findViewById(R.id.per_item_cost);
foodType = v.findViewById(R.id.fdTypeImg);
addBtn = v.findViewById(R.id.img_add);
removeBtn = v.findViewById(R.id.img_remove);
qty = v.findViewById(R.id.item_quantity);
priceCurnt = v.findViewById(R.id.txt_cost);
}
}

Listview with checkbox bug android

I have custom list view with checkbox, when I executed in my small mobile phone, if list view already had 5 items, then when I checked item 1, then item 5 will be checked also, if I checked item 5 then item 1 will be checked also, it happened with item (2-6,3-7,4-8, etc).
But if I had 4 items in my listview, it wont be happened. Here my listview adapter :
http://pastebin.com/mTEiXryf
Could you help me to solve my bug ? Thanks in advance
I suggest you to use Recyclerview
public class CardViewDataAdapter extends
RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private List<Student> stList;
public CardViewDataAdapter(List<Student> students) {
this.stList = students;
}
// Create new views
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.cardview_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final int pos = position;
viewHolder.tvName.setText(stList.get(position).getName());
viewHolder.tvEmailId.setText(stList.get(position).getEmailId());
viewHolder.chkSelected.setChecked(stList.get(position).isSelected());
viewHolder.chkSelected.setTag(stList.get(position));
viewHolder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Student contact = (Student) cb.getTag();
contact.setSelected(cb.isChecked());
stList.get(pos).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
// Return the size arraylist
#Override
public int getItemCount() {
return stList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public CheckBox chkSelected;
public Student singlestudent;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvName = (TextView) itemLayoutView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemLayoutView.findViewById(R.id.tvEmailId);
chkSelected = (CheckBox) itemLayoutView
.findViewById(R.id.chkSelected);
}
}
// method to access in activity after updating selection
public List<Student> getStudentist() {
return stList;
}
}
OR
If you want to use listview,then better you maintain Boolean array for checkbox,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;
}
}
Here is solution- You had added holder.chkbox.setOnClickListener at wrong place just put it at right place. Replace your code with this code
if(convertView == null) {
convertView = myInflater.inflate(R.layout.customviewitemcashier, null);
holder = new ViewHolder();
holder.tvitemcode = (TextView) convertView.findViewById(R.id.tvitemcode);
holder.tvitemname = (TextView) convertView.findViewById(R.id.tvitemname);
holder.tvprice = (TextView) convertView.findViewById(R.id.tvprice);
holder.tvsubtotal = (TextView) convertView.findViewById(R.id.tvsubtotal);
holder.edtqty = (EditText) convertView.findViewById(R.id.edtqty);
holder.imgincrease = (TextView) convertView.findViewById(R.id.imgincrease);
holder.imgdecrease = (TextView) convertView.findViewById(R.id.imgdecrease);
holder.imgitem= (ImageView) convertView.findViewById(R.id.imgitem);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.chkbox.isChecked()) {
SQLiteDatabase dbinsert = dbHelper.getWritableDatabase();
String SQLinsert = "INSERT INTO itemcheckedcontainer (`item_code`) VALUES (" +
"'" + DataProcessorResult.get(position).getItemCode() + "')";
dbinsert.execSQL(SQLinsert);
} else {
SQLiteDatabase dbdelete = dbHelper.getWritableDatabase();
String SQLdelete = "DELETE FROM itemcheckedcontainer WHERE item_code=" +
"'" + DataProcessorResult.get(position).getItemCode() + "'";
dbdelete.execSQL(SQLdelete);
}
}
});
Your problem solved.

Maintain the state of selected listview Imagebutton on scrolling

I try to implement add to favorites functionality in my app .I have two Image-buttons addToFavouritiesBtn and removeFromFavouritiesBtn in list-view . At a time only one Image-button get visible on selection.
My problem is , when I select addToFavouritiesBtn it gets selected , but when I scroll-down list-view and come back to that Image-button , it remains unselected.
Please tell me how to maintain state of the selected items on scrolling.
Here is my code.
public class Product{
private boolean selected = false;
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
ProdctListAdaptet.class
public class ProductListAdapter extends BaseAdapter {
private Activity activity;
private List<Product> productItems;
private Context context;
int pos;
int flag = 0 ;
public ProductListAdapter(Context context,Activity activity, List<Product> productItems,int flag) {
this.activity = activity;
this.productItems = productItems;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// ProductHolder holder = null;
final ProductHolder holder;
if (convertView == null) {
holder = new ProductHolder();
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.product_list_row_item, parent,false);
holder.thumbNail = (ImageView) convertView
.findViewById(R.id.product_image);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.btnAddFavourite = (ImageButton) convertView.findViewById(R.id.AddFavourites);
holder.btnRemoveFavourite = (ImageButton) convertView.findViewById(R.id.RemoveFavourites);
holder.btnAddFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
System.out.println("Add favourities");
pos = (Integer) v.getTag();
productItems.get(pos).setSelected(false);
holder.btnAddFavourite.setVisibility(View.GONE);
holder.btnRemoveFavourite.setVisibility(View.VISIBLE);
//notifyDataSetChanged();
}
});
holder.btnRemoveFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 2;
System.out.println("Remove favorities");
pos = (Integer) v.getTag();
productItems.get(pos).setSelected(true);
holder.btnAddFavourite.setVisibility(View.VISIBLE);
holder.btnRemoveFavourite.setVisibility(View.GONE);
// notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ProductHolder) convertView.getTag();
}
holder.btnAddFavourite.setTag(position);
holder.btnRemoveFavourite.setTag(position);
Product state = productItems.get(position);
System.out.println("Product position -----> " + state);
if (state.isSelected()) {
System.out.println("Selected state ******************* " + state.isSelected());
System.out.println("selected");
holder.btnAddFavourite.setVisibility(View.VISIBLE);
holder.btnRemoveFavourite.setVisibility(View.GONE);
} else {
System.out.println("Selected state ******************* " + state.isSelected());
System.out.println(" not selected");
holder.btnAddFavourite.setVisibility(View.GONE);
holder.btnRemoveFavourite.setVisibility(View.VISIBLE);
}
convertView.setTag(holder);
return convertView;
}
final Product product = (Product) productItems.get(position);
//final Product product = (Product) getItem(position);
holder.thumbNail.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
holder.title.setText(product.getName());
Picasso.with(activity).load(product.getHref())
.placeholder(R.drawable.ic_default_banner)
.into(holder.thumbNail);
private class ProductHolder {
TextView title;
ImageView thumbNail;
ImageButton btnAddFavourite;
ImageButton btnRemoveFavourite;
}
}
you have to use youradapetr.notifydatasetchanged() after change in dataset in your button onclick function
, in your case simply add notifyDataSetChanged(); like below in both function
holder.btnAddFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Add favourities");
int pos = (Integer) v.getTag();
productItems.get(pos).setSelected(false);
holder.btnAddFavourite.setVisibility(View.GONE);
holder.btnRemoveFavourite.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
});
I think the problem is inside the onClickListener. Use position which is coming as parameters instead of pos for setting the state inside your listeners.
holder.btnAddFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Add favourities");
productItems.get(position).setSelected(false);
holder.btnAddFavourite.setVisibility(View.GONE);
holder.btnRemoveFavourite.setVisibility(View.VISIBLE);
}
});
holder.btnRemoveFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Remove favorities");
productItems.get(position).setSelected(true);
holder.btnAddFavourite.setVisibility(View.VISIBLE);
holder.btnRemoveFavourite.setVisibility(View.GONE);
}
});
EDIT 1:-
Can your try below getView method. I think you are setting incorrect state in onclick listener. You are setting setSelected(true) in btnRemoveFavourite but it should be setSelected(false). Same applies for btnAddFavorite.
Please try below code and accept the answer if its correct.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ProductHolder holder = null;
if (convertView == null) {
holder = new ProductHolder();
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.product_list_row_item, parent, false);
holder.thumbNail = (ImageView) convertView.findViewById(R.id.product_image);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.btnAddFavourite = (ImageButton) convertView.findViewById(R.id.AddFavourites);
holder.btnRemoveFavourite = (ImageButton) convertView.findViewById(R.id.RemoveFavourites);
convertView.setTag(holder);
} else {
holder = (ProductHolder) convertView.getTag();
}
final Product product = productItems.get(position);
holder.btnAddFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
product.setSelected(true);
holder.btnAddFavourite.setVisibility(View.GONE);
holder.btnRemoveFavourite.setVisibility(View.VISIBLE);
}
});
holder.btnRemoveFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
product.setSelected(false);
holder.btnAddFavourite.setVisibility(View.VISIBLE);
holder.btnRemoveFavourite.setVisibility(View.GONE);
}
});
if (product.isSelected()) {
System.out.println("Selected state ******************* " + state.isSelected());
System.out.println("selected");
holder.btnAddFavourite.setVisibility(View.GONE);
holder.btnRemoveFavourite.setVisibility(View.VISIBLE);
} else {
System.out.println("Selected state ******************* " + state.isSelected());
System.out.println(" not selected");
holder.btnAddFavourite.setVisibility(View.VISIBLE);
holder.btnRemoveFavourite.setVisibility(View.GONE);
}
return convertView;
}
The Issue:
getView() in your adapter gets called from time to time. As a result, if the selected state is not set for the button, it will revert to the original state.
Solution:
Keep a boolean in the model class [Product] with getters and setters:
boolean didSelect;
public boolean isDidSelect() {
return didSelect;
}
public void setDidSelect(boolean didSelect) {
this.didSelect = didSelect;
}
In getView(), depending on the value in the boolean set the selection of the button.
Here i am giving a simple demo for you,You Can update it according your requirement,I hope you will get your Solution.
public class MainActivity extends Activity {
String s[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y",
"Z" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Product> products = new ArrayList<Product>();
ListView list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < s.length; i++) {
Product item = new Product();
item.setCheck(false);
item.setName(s[i].toString());
products.add(item);
}
ProductListAdapter ac = new ProductListAdapter(MainActivity.this, R.layout.row,
products);
list.setAdapter(ac);
}// on create method end
class ProductListAdapter extends BaseAdapter {
private List<Product> productItems;
Context context;
int layoutId;
public ProductListAdapter(Context context, int layoudId, List<Product> productItems) {
// super(context,productItems);
this.layoutId = layoudId;
this.context = context;
this.productItems = productItems;
}
public class ProductHolder {
ImageView image;
TextView name;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ProductHolder holder;
Product rowitems = productItems.get(position);
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(layoutId, parent, false);
holder = new ProductHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.image = (ImageView) convertView
.findViewById(R.id.invite_click);
holder.image.setBackgroundResource(R.drawable.green);
convertView.setTag(holder);
}
else {
holder = (ProductHolder) convertView.getTag();
}
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (productItems.get(position).isCheck) {
productItems.get(position).isCheck = false;
// holder.image.setImageBitmap(null);
holder.image.setBackgroundResource(R.drawable.green);
} else {
productItems.get(position).isCheck = true;
holder.image
.setBackgroundResource(R.drawable.green_tick);
}
}
});
if (productItems.get(position).isCheck) {
productItems.get(position).isCheck = true;
holder.image.setBackgroundResource(R.drawable.green_tick);
} else {
productItems.get(position).isCheck = false;
holder.image.setImageBitmap(null);
holder.image.setBackgroundResource(R.drawable.green);
}
holder.name.setText(rowitems.getName());
Log.e("name----->", productItems.get(position).toString());
return convertView;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return productItems.indexOf(getItem(position));
}
}
}

how to redirect to different Activity in android on item click

Here is My code for item Click and print data in list view .
listView = (ListView) layout.findViewById(R.id.listView1);
Notifcationadapter adapter = new Notifcationadapter(this, notifies);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View parentView = (View) view.getParent();
TextView value1 = ((TextView) parentView.findViewById(R.id.title));
String value = value1.getText().toString();
if (value.equals("Post"))
Toast.makeText(this, "Post", 1000).show();
if (value.equals("Request For travelling"))
Toast.makeText(this, "Request for travelling", 1000).show();
}
Here is my adapter :
public class Notifcationadapter extends BaseAdapter {
private static ArrayList<Notify> values;
Context context;
// List<RowItem> rowItems;
ViewHolder holder = null;
LinearLayout linear2;
DataBaseManager dbManager = new DataBaseManager(context);
ArrayList<Notify> notifies;
public Notifcationadapter(Context context, ArrayList<Notify> notifies) {
super();
this.context = context;
this.notifies = notifies;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView yesimage;
ImageView noimage;
TextView revresetime;
LinearLayout linear2;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notifcationlistitem, null);
holder = new ViewHolder();
holder.linear2 = (LinearLayout) convertView.findViewById(R.id.linear2);
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.yesimage = (ImageView) convertView.findViewById(R.id.imageView1);
holder.noimage = (ImageView) convertView.findViewById(R.id.imageView2);
holder.revresetime = (TextView) convertView.findViewById(R.id.revresetime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.txtTitle.setText("Title");
String statustype = notifies.get(position).getNotificationType();
if (statustype.equals("1")) {
holder.txtDesc.setText(notifies.get(position).getNotificationDescrpiton());
holder.revresetime.setText(Functions.setLastSeenNotifcationTime(notifies.get(position).getNotificationDatetime()));
holder.txtTitle.setText("Request For travelling");
holder.yesimage.setVisibility(View.VISIBLE);
holder.noimage.setVisibility(View.VISIBLE);
} else {
holder.txtDesc.setText(notifies.get(position).getNotificationDescrpiton());
holder.txtTitle.setText("Post");
holder.revresetime.setText(Functions.setLastSeenNotifcationTime(notifies.get(position).getNotificationDatetime()));
holder.yesimage.setVisibility(View.GONE);
holder.noimage.setVisibility(View.GONE);
}
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
} else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
holder.yesimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Yes", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
holder.noimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "NO", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
return convertView;
}
#Override
public int getCount() {
return notifies.size();
}
#Override
public Object getItem(int position) {
return notifies.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
I am displaying data in List view i wan i want to apply on item click function so that if text view list display post in list then its item click it should Print post if it Request for traveling then it should show Request for travel but i am unable to do this please help where am doing wrong .
you are getting the same value because of this line
TextView value1 = ((TextView) parentView.findViewById(R.id.title));
to get the String value in your adapter or arraylist you can do something like this.
i assume you have arraylist of objects
//you arraylist contains object/class
String value1 = notifies.get(position).getTitle();
and using the adapter
String value1 = adapter.getItem(position);
then #Override the getItem() function in your adapter
#Override
public String getItem(int position){
return notifies.get(position).getTitle();
}
then to move to other activity according to your if statement
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View parentView = (View) view.getParent();
String value = notifies.get(position).getTitle();
Intent i = null;
if (value.equals("Post")){
i = new Intent(context,PostActivity.class);
}
else if (value.equals("Request For travelling")){
i = new Intent(context,RequestActivity.class);
}
if(i !=null){
startActivity(i);
}
}
I think you should use int position of onItemClick.
and then use if(notifies.get(position).getNotificationType() == 1)
it will be faster and should effectively work also.
First remove the onitemclick listener from activity. and use this code -
listView.setOnItemClickListener(this); // remove this line
as well as remove onitem click-
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
View parentView = (View) view.getParent();
TextView value1 = ((TextView) parentView.findViewById(R.id.title));
String value = value1.getText().toString();
if (value.equals("Post")) {
Toast.makeText(this, "Post", 1000).show();
}
if (value.equals("Request For travelling")) {
Toast.makeText(this, "Request for travelling", 1000).show();
}
}
**just add convertview click listener**
public class Notifcationadapter extends BaseAdapter {
private static ArrayList<Notify> values;
Context context;
// List<RowItem> rowItems;
ViewHolder holder = null;
LinearLayout linear2;
DataBaseManager dbManager = new DataBaseManager(context);
ArrayList<Notify> notifies;
public Notifcationadapter(Context context, ArrayList<Notify> notifies) {
super();
this.context = context;
this.notifies = notifies;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView yesimage;
ImageView noimage;
TextView revresetime;
LinearLayout linear2;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notifcationlistitem, null);
holder = new ViewHolder();
holder.linear2 = (LinearLayout) convertView
.findViewById(R.id.linear2);
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.yesimage = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.noimage = (ImageView) convertView
.findViewById(R.id.imageView2);
holder.revresetime = (TextView) convertView
.findViewById(R.id.revresetime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.txtTitle.setText("Title");
String statustype = notifies.get(position).getNotificationType();
if (statustype.equals("1")) {
holder.txtDesc.setText(notifies.get(position)
.getNotificationDescrpiton());
holder.revresetime.setText(Functions
.setLastSeenNotifcationTime(notifies.get(position)
.getNotificationDatetime()));
holder.txtTitle.setText("Request For travelling");
holder.yesimage.setVisibility(View.VISIBLE);
holder.noimage.setVisibility(View.VISIBLE);
}
else {
holder.txtDesc.setText(notifies.get(position)
.getNotificationDescrpiton());
holder.txtTitle.setText("Post");
holder.revresetime.setText(Functions
.setLastSeenNotifcationTime(notifies.get(position)
.getNotificationDatetime()));
holder.yesimage.setVisibility(View.GONE);
holder.noimage.setVisibility(View.GONE);
}
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
}
else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
holder.yesimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(context, "Yes", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
holder.noimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "NO", 10000).show();
holder.linear2.setVisibility(View.INVISIBLE);
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// write your code to redirect to another activity like this way
Intent i = new Intent(context,
Youractivity.class);
context.startActivity(i);
}
});
return convertView;
}
#Override
public int getCount() {
return notifies.size();
}
#Override
public Object getItem(int position) {
return notifies.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}

Categories

Resources