Android: radio group in list view not working - android

When i click the radio group from the first item all the
corresponding items should be selected when the check box is checked
if the check box is not checked then the corresponding items radio
button should not be checked.
if i click in between then first item radio button should be
deselect else if i click the unchecked radio button the check box
should be checked and radio button also be checked. This is what i
want to achieve in this.
My problem from the below code is when i click the first item all the items getting selected but if i click another item in between the first item is getting deselected and the button which i clicked is re positioned
TeacherAssessmentFragmentChild.java
package com.example.playit;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
#SuppressLint("NewApi")
public class TeacherAssessmentFragmentChild extends Fragment {
static Context context;
ArrayList<TeacherAssessmentFragmentChildContainer> assessmentContainer=new ArrayList<>();
View rootView ;
ListView lstassessment;
TeacherAssessmentFragmentChildListAdapter listAdapter;
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.teacher_asseessment_view_fragment_child,
container, false);
Initialize();
context = TeacherAssessmentFragment.context;
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chapter", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 1 Algebra", "1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 2 Trignomentry", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 3 Integration", "4"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 4 Differentiation", "3"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 5 Abacus", "2"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 6 Numbersystem", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 7 Algebra", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 8 Algebra", "2"));
listAdapter=new TeacherAssessmentFragmentChildListAdapter(context, 0, assessmentContainer);
lstassessment.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
return rootView;
}
public void Initialize() {
lstassessment=(ListView) rootView.findViewById(R.id.teacher_assessment_view_fragment_clild_assessment_list);
}
}
TeacherAssessmentFragmentChildContainer.java
package com.example.playit;
public class TeacherAssessmentFragmentChildContainer {
String chapterName,moduleSelected;
Boolean ismoduleActive;
public TeacherAssessmentFragmentChildContainer(String chapterName,
String moduleSelected) {
super();
this.chapterName = chapterName;
this.moduleSelected = moduleSelected;
if(moduleSelected.equalsIgnoreCase("-1"))
ismoduleActive=false;
else
ismoduleActive=true;
}
public Boolean getIsmoduleActive() {
return ismoduleActive;
}
public void setIsmoduleActive(Boolean ismoduleActive) {
this.ismoduleActive = ismoduleActive;
}
public String getChapterName() {
return chapterName;
}
public String getModuleSelected() {
return moduleSelected;
}
public void setModuleSelected(String moduleSelected) {
this.moduleSelected = moduleSelected;
}
}
TeacherAssessmentFragmentChildListAdapter
package com.example.playit;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
#SuppressLint("NewApi")
public class TeacherAssessmentFragmentChildListAdapter extends
ArrayAdapter<TeacherAssessmentFragmentChildContainer> {
static Context context;
static ArrayList<TeacherAssessmentFragmentChildContainer> container = new ArrayList<>();
ViewHolder holder;
static int checkBoxCount = 0, radioCount = 0, selectedPosition = -1;
public TeacherAssessmentFragmentChildListAdapter(Context context,
int resource,
ArrayList<TeacherAssessmentFragmentChildContainer> container) {
super(context, resource, container);
this.context = context;
this.container = container;
}
#Override
public int getViewTypeCount() {
// Count=Size of ArrayList.
return container.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
public class ViewHolder {
TextView txvchapterName;
CheckBox ckbselectName;
RadioGroup rgassessment;
RadioButton assessment1, assessment2, assessment3, assessment4,
assessment5;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// System.out.println("getview:" + position + " " + convertView);
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater
.inflate(
R.layout.teacher_assessment_view_fragment_child_list_adapter,
parent, false);
holder = new ViewHolder();
holder.txvchapterName = (TextView) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_chapter);
holder.ckbselectName = (CheckBox) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_select);
holder.rgassessment = (RadioGroup) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment_group);
holder.assessment1 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment1);
holder.assessment2 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment2);
holder.assessment3 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment3);
holder.assessment4 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment4);
holder.assessment5 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment5);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
if (position == 0) {
holder.assessment1.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment2.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment3.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment4.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment5.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment1.setText("");
holder.assessment2.setText("");
holder.assessment3.setText("");
holder.assessment4.setText("");
holder.assessment5.setText("");
} else {
holder.assessment1.setButtonDrawable(android.R.color.transparent);
holder.assessment2.setButtonDrawable(android.R.color.transparent);
holder.assessment3.setButtonDrawable(android.R.color.transparent);
holder.assessment4.setButtonDrawable(android.R.color.transparent);
holder.assessment5.setButtonDrawable(android.R.color.transparent);
holder.assessment1.setText("M1");
holder.assessment2.setText("M2");
holder.assessment3.setText("M3");
holder.assessment4.setText("M4");
holder.assessment5.setText("M5");
}
holder.ckbselectName.setTag(position);
holder.rgassessment.setTag(position);
SetCheckedRbn(container.get(position).getModuleSelected());
SetCheckedChb(container.get(position).ismoduleActive);
holder.ckbselectName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
System.out.println("selectedPosition : "+selectedPosition);
System.out.println("container.get(selectedPosition).getIsmoduleActive() : "+container.get(selectedPosition).getIsmoduleActive());
if(selectedPosition==0){
for(int i=0;i<container.size();i++){
if(!container.get(i).getIsmoduleActive()){
container.get(i).setIsmoduleActive(true);
container.get(i).setModuleSelected("0");
}
else {
container.get(i).setIsmoduleActive(false);
container.get(i).setModuleSelected("-1");
}
}
}
else {
if(!container.get(selectedPosition).getIsmoduleActive()){
container.get(selectedPosition).setIsmoduleActive(true);
container.get(selectedPosition).setModuleSelected("0");
}
else {
container.get(selectedPosition).setIsmoduleActive(false);
container.get(selectedPosition).setModuleSelected("-1");
}
}
System.out.println("container.get(selectedPosition).getIsmoduleActive() : "+container.get(selectedPosition).getIsmoduleActive());
notifyDataSetChanged();
}
});
holder.txvchapterName.setText(container.get(position).getChapterName());
holder.rgassessment
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
selectedPosition = (Integer) group.getTag();
View radioButtonView = group.findViewById(checkedId);
RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
int idx = group.indexOfChild(radioButtonView);
if (selectedPosition == 0 && checkedRadioButton.isChecked() ) {
for (int i = 0; i < container.size(); i++) {
if (container.get(i).getIsmoduleActive() || i==0 ){
container.get(i).setModuleSelected("" + idx);
}
else if(i!=0){
container.get(i).setModuleSelected("-1");
container.get(i).setIsmoduleActive(false);
}
}
}
else if(selectedPosition !=0){
container.get(selectedPosition).setIsmoduleActive(
true);
container.get(selectedPosition).setModuleSelected(
"" + idx);
}
checkrb();
}
});
return row;
}
public void SetCheckedRbn(String str) {
switch (str) {
case "0":
holder.assessment1.setChecked(true);
break;
case "1":
holder.assessment2.setChecked(true);
break;
case "2":
holder.assessment3.setChecked(true);
break;
case "3":
holder.assessment4.setChecked(true);
break;
case "4":
holder.assessment5.setChecked(true);
break;
default:
holder.assessment1.setChecked(false);
holder.assessment2.setChecked(false);
holder.assessment3.setChecked(false);
holder.assessment4.setChecked(false);
holder.assessment5.setChecked(false);
break;
}
}
public void SetCheckedChb(Boolean isactive) {
if (isactive)
holder.ckbselectName.setChecked(true);
else
holder.ckbselectName.setChecked(false);
}
public void checkrb() {
int rbcount=0,chcount=0;
String str="";
for(int i=0;i<container.size();i++) {
str=container.get(i).getModuleSelected();
if(str!="-1"){
break;
}
}
for(int i=1;i<container.size() && str!="";i++) {
if(str.equals(container.get(i).getModuleSelected()) && container.get(i).getIsmoduleActive()){
rbcount++;
str=container.get(i).getModuleSelected();
}
if(container.get(i).getIsmoduleActive())
chcount++;
}
if(rbcount!=chcount)
container.get(0).setModuleSelected("-1");
else
container.get(0).setModuleSelected(str);
if(rbcount==container.size())
container.get(0).setIsmoduleActive(true);
else
container.get(0).setIsmoduleActive(false);
notifyDataSetChanged();
}
public void checkchb() {
int chcount=0;
for(int i=0;i<container.size();i++) {
if(container.get(i).getIsmoduleActive())
chcount++;
}
if(chcount==(container.size()-1)){
container.get(0).setIsmoduleActive(true);
}
else
container.get(0).setIsmoduleActive(false);
notifyDataSetChanged();
}
}

Related

Cannot remove item from Shopping Cart android studio

I referred [this][1] and [this][2] site and tried to modify it according to my own needs. Problem is I can't remove an item from the cart. I have tried everything including searching for solutions in stackoverflow and google but no luck.
Here is my CatalogActivity.java
package com.comlu.sush.shoppingcart;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
public class CatalogActivity extends AppCompatActivity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false,false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
ShoppingCartHelper.java
package com.comlu.sush.shoppingcart;
import android.content.res.Resources;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
private static List<Product> catalog;
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();
public static List<Product> getCatalog(Resources res){
if(catalog == null) {
catalog = new Vector<Product>();
catalog.add(new Product("Dead or Alive", res
.getDrawable(R.drawable.first),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Switch", res
.getDrawable(R.drawable.second),
"Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.third),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}
return catalog;
}
public static void setQuantity(Product product, int quantity) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
// If the quantity is zero or less, remove the products
if(quantity <= 0) {
if(curEntry != null)
removeProduct(product);
return;
}
// If a current cart entry doesn't exist, create one
if(curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity);
cartMap.put(product, curEntry);
return;
}
// Update the quantity
curEntry.setQuantity(quantity);
}
public static int getProductQuantity(Product product) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
if(curEntry != null)
return curEntry.getQuantity();
return 0;
}
public static void removeProduct(Product product) {
cartMap.remove(product);
}
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
}
ShoppingCartActiity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShoppingCartActivity extends AppCompatActivity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true,true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mProductAdapter.toggleSelection(position);
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if(mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
}
}
ProductDetailsActivity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ProductDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
final int result=0;
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
}
ProductAdapter.java
package com.comlu.sush.shoppingcart;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
private boolean mShowCheckbox;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity, boolean showCheckbox) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
mShowCheckbox = showCheckbox;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
item.productCheckbox = (CheckBox) convertView.findViewById(R.id.CheckBoxSelected);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
if(!mShowCheckbox) {
item.productCheckbox.setVisibility(View.GONE);
} else {
if(curProduct.selected == true)
item.productCheckbox.setChecked(true);
else
item.productCheckbox.setChecked(false);
}
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
public void removeSelected() {
for(int i=mProductList.size()-1; i>=0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
CheckBox productCheckbox;
}
}
You should move data manipulation to the adapter, and design-wise it would make sense and might also fix the problem you're telling us.
Write this method in your ProductAdapter:
public void removeSelected() {
for(int i = mProductList.size()-1; i >= 0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
Update your OnClickListener (in your ShoppingCartActiity of course):
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
Edit
I noticed that you aren't applying OOP's concept of encapsulation here. That is, ShoppingCartActiity shouldn't be making changes to the data which belongs to your adapter.
So, just create public methods inside the ProductAdapter for item for selection, etc and call them from ShoppingCartActiity as needed.
Copy this method in your ProductAdapter:
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
mProductAdapter.toggleSelection(position); will replace following code ShoppingCartActiity:
Product selectedProduct = mCartList.get(position);
if(selectedProduct.selected == true)
selectedProduct.selected = false;
else
selectedProduct.selected = true;
mProductAdapter.notifyDataSetInvalidated();
Edit2
The problem is that the ShoppingCartActiity takes items from ShoppingCartEntry on starting up, but it never writes back the changes to it when you remove items.
update your removeButton's onClick() to:
mProductAdapter.removeSelected();
if (product.selected) {
// set products which are remaining in the adapter
ShoppingCartHelper.setProducts(mProductAdapter.getProducts());
}
ShoppingCartHelper.setProducts() would replace the old data with the passed one:
public static void setProducts(ArrayList<Product> products) {
catalog = new Vector<Product>();
for (Product product : products) {
catalog.add(product);
}
}
mProductAdapter.getProducts() will just return the list of Products, like:
public List<Product> getProducts() {
return mProductList;
}
you just have to remove selected item from list, and after adapter.notifiyDataSetChanged() it will refresh the adapter.
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Loop through and remove all the products that are selected
// Loop backwards so that the remove works correctly
for(int i=mCartList.size()-1; i>=0; i--) {
if(mCartList.get(i).selected) {
mCartList.remove(i);
//mProductAdapter.removeSelected();
}
}
if(mProductAdapter!=null)
mProductAdapter.notifyDataSetChanged();
}
});

Updating TextView inside Header ListView

I'm trying to update my TextView when my onItenClick event fires, I have several TextViews, they are created as many I want inside my row template, but here goes the problem, when I try to set this TextView value it's acctually getting setted, but another textview, is also setted, with the same value I have on idea of the why to this behavior, but have no idea how to fix it.
My idea:
I my getRowView method (when I scroll the list), I'm seeing an
unusual behavior, once after I set some value to one of my itens, it
keep changing the text view that got this value. So I think here is
the core of the problem.
PS: I'm using the component HeaderListView, if you get another suggestion of framework to do the same thing, I would really appreciate.
PS2: Here goes my code:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import br.com.soutsapp.souts.R;
import br.com.soutsapp.souts.model.Menu;
import br.com.soutsapp.souts.model.Product;
import br.com.soutsapp.souts.model.modelview.OrderItem;
import br.com.soutsapp.souts.userInterface.activity.SectionAdapter;
import br.com.soutsapp.souts.userInterface.adapter.HeaderListView;
public class MenuFragment extends Fragment {
private Context mContext;
private List<OrderItem> itens;
private Menu menu;
public MenuFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_menu, container, false);
mContext = getContext();
itens = new ArrayList<>();
menu = new Menu();
final String[] sec1 = {"aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa","aaaaaaaa"};
final String[] sec2 = {"bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb","bbbbbbbb"};
final String[] sec3 = {"cccccccc","cccccccc","cccccccc","cccccccc","cccccccc","cccccccc","cccccccc"};
final String[] sec4 = {"dddddddd","dddddddd","dddddddd","dddddddd","dddddddd","dddddddd","dddddddd"};
HeaderListView lv = (HeaderListView) v.findViewById(R.id.lv_menu_items);
lv.setAdapter(new SectionAdapter() {
#Override
public int numberOfSections() {
return menu.getMenuSessions().size();
}
#Override
public int numberOfRows(int section) {
return menu.getMenuSessions().get(section).size();
}
#Override
public Object getRowItem(int section, int row) {
return menu.getMenuSessions().get(section).get(row);
}
#Override
public boolean hasSectionHeaderView(int section) {
return true;
}
#Override
public View getRowView(int section, int row, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(getResources().getLayout(R.layout.menu_item_row), null);
}
//Product product = (Product)getRowItem(section, row);
//convertView.setId(product.getId());
TextView tvMenuItemName = (TextView) convertView.findViewById(R.id.tv_menu_item_name);
TextView tvMenuItemPrice = (TextView) convertView.findViewById(R.id.tv_price);
String itemName = ((Product)getRowItem(section,row)).getName();
tvMenuItemName.setText(itemName);
String itemPrice = String.valueOf(((Product) getRowItem(section, row)).getPrice());
tvMenuItemPrice.setText(itemPrice);
final int mySection = section;
final int myRow = row;
final TextView tvQuantity = (TextView) convertView.findViewById(R.id.tv_quantity);
tvQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Product product = (Product) getRowItem(mySection, myRow);
if (tvQuantity.getText().equals("1") && !tvQuantity.getText().equals("")){
tvQuantity.setText("");
OrderItem itenToRemove = null;
for(OrderItem item: itens){
if(item.getProductId() == product.getId()){
itenToRemove = item;
break;
}
}
itens.remove(itenToRemove);
}
else{
for(OrderItem item: itens){
if(item.getProductId() == product.getId()){
int quantity = item.getQuantity();
item.setQuantity(--quantity);
tvQuantity.setText(String.valueOf(item.getQuantity()));
break;
}
}
}
}
});
return convertView;
}
#Override
public int getSectionHeaderViewTypeCount() {
return 1;
}
#Override
public int getSectionHeaderItemViewType(int section) {
return section % 1;
}
#Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = (TextView) getActivity().getLayoutInflater().inflate(getResources().getLayout(android.R.layout.simple_list_item_1), null);
}
if (getSectionHeaderItemViewType(section) == 0) {
((TextView) convertView).setText("Header for section " + section);
} else {
((TextView) convertView.findViewById(android.R.id.text1)).setText("Header for section " + section);
}
switch (section) {
case 0:
convertView.setBackgroundColor(getResources().getColor(R.color.Blue_Jay));
break;
case 1:
convertView.setBackgroundColor(getResources().getColor(R.color.Yellow));
break;
case 2:
convertView.setBackgroundColor(getResources().getColor(R.color.Red_Wine));
break;
}
return convertView;
}
#Override
public void onRowItemClick(AdapterView<?> parent, View view, int section, int row, long id) {
super.onRowItemClick(parent, view, section, row, id);
//Product p = (Product)view.getTag();
TextView tvQuantity = (TextView) view.findViewById(R.id.tv_quantity);
Product p = menu.getMenuSessions().get(section).get(row);
//Product p = (Product) getRowItem(section, row);
boolean exist = false;
for(OrderItem item : itens){
if(item.getProductId() == p.getId()){
int actualQuantity = item.getQuantity();
item.setQuantity(++actualQuantity);
tvQuantity.setText(String.valueOf(item.getQuantity()));
exist = true;
}
}
if(!exist){
itens.add(new OrderItem(p.getId(), 1));
tvQuantity.setText("1");
}
}
});
return v;
}
}
Here goes on screenshot, I had touch the "Smirnoff dose" item, and both "Smirnoff dose" and "Água" have their textviews values changed.

How should I pass an Arraylist to BaseAdapter in android?

I have the following problem. I am not able pass the Arraylist to another Activity which extends BaseActivity.
ListViewAdapter.java
package com.example.coherendz.uobgoldandsilver;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListViewAdapter extends BaseAdapter {
ArrayList<String> myList = new ArrayList();
ArrayList<String> selectedList = new ArrayList();
LayoutInflater inflater,layout;
Context context;
private ArrayList currency,weight,Buy,Sell;
ArrayList<String> names= new ArrayList<String>();
Activity a;
public ListViewAdapter(ArrayList myList,ArrayList names,ArrayList currency,ArrayList weight,ArrayList Buy,ArrayList Sell, Context context) {
this.myList = myList;
this.names = names;
this.currency = currency;
this.weight = weight;
this.Buy = Buy;
this.Sell = Sell;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
public ListViewAdapter(Context context,ArrayList<String> selectedList){
layout = LayoutInflater.from(context);
this.selectedList = selectedList;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Object getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder=null;
if(convertView == null) {
convertView = inflater.inflate(R.layout.custom_row, null);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
String name="",weig="",buy="",sell="";
String temp_name="";
if(selectedList.size()== 7 || selectedList.isEmpty())
{
/*for(int i =0;i<=names.size();i++)
{
for (int j = 1; j < names.size(); j++)
{
//name = names.get(i).toString();
name = names.get(position).toString();
temp_name = names.get(j).toString();
mViewHolder.tvTitle.setText(name);
if (temp_name.isEmpty()) {
temp_name = name;
mViewHolder.tvTitle.setText(temp_name);
} else {
mViewHolder.tvTitle.setText(name);
}
}
names.clear();
}*/
/*for(String s : names)
{
name = names.get(position).toString();
if(name.isEmpty())
{
mViewHolder.tvTitle.setText(temp_name);
}
else
{
mViewHolder.tvTitle.setText(name);
}
temp_name = name;
}*/
name = names.get(position).toString();
weig = weight.get(position).toString();
buy = Buy.get(position).toString();
sell = Sell.get(position).toString();
mViewHolder.tvTitle.setText(name);
mViewHolder.tvQty.setText(weig);
mViewHolder.tvBuy.setText(buy);
mViewHolder.tvSell.setText(sell);
}
else
{
StringBuilder string1 = new StringBuilder();
for(int i=0; i<selectedList.size();i++){
string1.append(selectedList.get(i).toString());
}
Log.i("Srikanth.M",string1.toString());
for(int j = 0;j<names.size();j++)
{
if(selectedList.contains(names.get(j)))
{
name = names.get(position).toString();
weig = weight.get(position).toString();
buy = Buy.get(position).toString();
sell = Sell.get(position).toString();
mViewHolder.tvTitle.setText(name);
mViewHolder.tvQty.setText(weig);
mViewHolder.tvBuy.setText(buy);
mViewHolder.tvSell.setText(sell);
}
}
}
return convertView;
}
private class MyViewHolder {
TextView tvTitle,tvQty,tvBuy,tvSell;
MyViewHolder(View v){
tvTitle = (TextView) v.findViewById(R.id.tvName);
tvQty = (TextView) v.findViewById(R.id.tvQty);
tvBuy = (TextView) v.findViewById(R.id.tvBuy);
tvSell = (TextView) v.findViewById(R.id.tvSell);
}
}
}
Settings.java
package com.example.coherendz.uobgoldandsilver;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import java.util.ArrayList;
public class Settings extends ActionBarActivity {
private String arbo,cas;
ArrayList<String> selectedList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actvity_settings);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_settings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_click) {
ListViewAdapter adapter = new ListViewAdapter(this,selectedList);
finish();
}
return super.onOptionsItemSelected(item);
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch (view.getId()) {
case R.id.cbArgor:
if (checked) {
CheckBox arbor = (CheckBox) findViewById(R.id.cbArgor);
arbo = arbor.getText().toString();
Log.i("Srikanth", arbo);
selectedList.add(arbo);
}
// Put some meat on the sandwich
else {
selectedList.remove(0);
Log.i("Srikanth","Removed Argo");
}
// Remove the meat
break;
case R.id.cbCast:
if (checked) {
CheckBox cast = (CheckBox) findViewById(R.id.cbCast);
cas = cast.getText().toString();
Log.i("Srikanth", cas);
selectedList.add(cas);
}
// Cheese me
else {
selectedList.remove(cas);
Log.i("Srikanth","Removed Cast");
}
// I'm lactose intolerant
break;
case R.id.cbGoldCertificate:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbGoldSavings:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbGoldBullion:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbPampGoldBars:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbPampGoldBarsWithHook:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbSilverPassbookAccount:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
}
StringBuilder string = new StringBuilder();
for(int i=0; i<selectedList.size();i++){
string.append(selectedList.get(i).toString());
}
Log.i("Srikanth.S",string.toString());
}
}
I am not able to retrieve the values of selectedList.
Any Suggestions ?
Because you are adding values to selectedList and not to your adapter data.
Step1: Add those methods in your adapter:
public void addItem(String item){
this.selectedList.add(item);
notifyDataSetChanged();
}
public void removeItem(int position){
this.selectedList.remove(position);
notifyDataSetChanged();
}
Step2: In your Settings Acitvity:
1) Make ListViewAdapter adapter as class variable.
2) Replace all those calls:
selectedList.add(...); by adapter.addItem(...);
and selectedList.remove(...); by adapter.removeItem(...);

RadioButton inside listview

I am using RadioGroup as a row Item inside listview. RadioGroup has 5 radio buttons and I have like 1000 rows. I am not able to mange state of radio buttons.I have tried Map for storing position and checked state. I have even tried making Class and saving checked state and radio button id with setTag() & getTag(). No luck yet. Any suggestions?
Code
Adapter class
package com.example.adapters;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.R;
import com.example.models.AnswerStateModel;
public class AnswerKeyAdapter extends ArrayAdapter<AnswerStateModel> {
private Activity activity;
private List<AnswerStateModel> test;
Toast t = null;
public AnswerKeyAdapter(Activity activity, List<AnswerStateModel> temp) {
super(activity, R.layout.row_item_answer_key, temp);
this.activity = activity;
this.test = temp;
}
#Override
public int getCount() {
return test.size();
}
#Override
public AnswerStateModel getItem(int position) {
return test.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int currentPosition=position;
View view=null;
if (convertView == null) {
final ViewHolder holder = new ViewHolder();
view = LayoutInflater.from(activity).inflate(
R.layout.row_item_answer_key, parent,false);
holder.lblAnswerId = (TextView) view.findViewById(R.id.lblAnswerId);
holder.rdGroup = (RadioGroup)view.findViewById(R.id.rdGroup);
holder.btnA = (RadioButton) view.findViewById(R.id.btnA);
holder.btnB = (RadioButton) view.findViewById(R.id.btnB);
holder.btnC = (RadioButton) view.findViewById(R.id.btnC);
holder.btnD = (RadioButton) view.findViewById(R.id.btnD);
holder.btnE = (RadioButton) view.findViewById(R.id.btnE);
holder.btnWhat = (Button) view.findViewById(R.id.btnWhat);
view.setTag(holder);
holder.rdGroup.setTag(test.get(position));
holder.rdGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
AnswerStateModel model=(AnswerStateModel) holder.rdGroup.getTag();
switch (checkedId) {
case R.id.btnA:
model.setChecked(holder.btnA.isChecked());
model.setBtnId(holder.btnA.getId());
break;
case R.id.btnB:
model.setChecked(holder.btnB.isChecked());
model.setBtnId(holder.btnB.getId());
break;
case R.id.btnC:
model.setChecked(holder.btnC.isChecked());
model.setBtnId(holder.btnC.getId());
break;
case R.id.btnD:
model.setChecked(holder.btnD.isChecked());
model.setBtnId(holder.btnD.getId());
break;
case R.id.btnE:
model.setChecked(holder.btnE.isChecked());
model.setBtnId(holder.btnE.getId());
break;
default:
break;
}
}
});
} else{
view=convertView;
((ViewHolder) view.getTag()).rdGroup.setTag(test.get(position));
}
final ViewHolder holder = (ViewHolder) view.getTag();
AnswerStateModel model=(AnswerStateModel)getItem(currentPosition);
holder.btnA.setChecked(false);
holder.btnB.setChecked(false);
holder.btnC.setChecked(false);
holder.btnD.setChecked(false);
holder.btnE.setChecked(false);
switch (model.getBtnId()) {
case R.id.btnA:
holder.btnA.setChecked(test.get(position).isChecked());
break;
case R.id.btnB:
holder.btnB.setChecked(test.get(position).isChecked());
break;
case R.id.btnC:
holder.btnC.setChecked(test.get(position).isChecked());
break;
case R.id.btnD:
holder.btnD.setChecked(test.get(position).isChecked());
break;
case R.id.btnE:
holder.btnE.setChecked(test.get(position).isChecked());
break;
default:
break;
}
holder.lblAnswerId.setText(position+1+"");
holder.btnWhat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.isSelected())
v.setSelected(false);
else
v.setSelected(true);
}
});
return view;
}
private static class ViewHolder {
private TextView lblAnswerId;
private RadioButton btnA;
private RadioButton btnB;
private RadioButton btnC;
private RadioButton btnD;
private RadioButton btnE;
private RadioGroup rdGroup;
private Button btnWhat;
}
void showToast(String text) {
if (t != null)
t.cancel();
t = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
t.show();
}
}
Pojo class
package com.example.models;
public class AnswerStateModel {
private boolean isChecked=false;
private int btnId=0;
private int currentPosition=0;
private String correctAns="";
private int btnPosition=0;
public int getBtnPosition() {
return btnPosition;
}
public void setBtnPosition(int btnPosition) {
this.btnPosition = btnPosition;
}
public String getCorrectAns() {
return correctAns;
}
public void setCorrectAns(String correctAns) {
this.correctAns = correctAns;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public int getBtnId() {
return btnId;
}
public void setBtnId(int btnId) {
this.btnId = btnId;
}
public int getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(int currentPosition) {
this.currentPosition = currentPosition;
}
}
Solved it! Used SparseIntArray
Here is the complete code.
/**
*
*/
package com.example.adapters;
import java.util.ArrayList;
import android.app.Activity;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.R;
import com.example.models.AnswerStateModel;
import com.example.utils.Config;
public class AnswerKeyAdapter extends ArrayAdapter<AnswerStateModel> {
private Activity activity;
private ArrayList<AnswerStateModel> mAnswerList;
Toast t = null;
private SparseIntArray mSpCheckedState=new SparseIntArray();
public AnswerKeyAdapter(Activity activity, ArrayList<AnswerStateModel> mAnswerList) {
super(activity, R.layout.row_item_answer_key, mAnswerList);
this.activity = activity;
this.mAnswerList = mAnswerList;
}
#Override
public int getCount() {
return mAnswerList.size();
}
#Override
public AnswerStateModel getItem(int position) {
return mAnswerList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(activity).inflate(
R.layout.row_item_answer_key, parent, false);
holder.lblAnswerId = (TextView) convertView.findViewById(R.id.lblAnswerId);
holder.rdGroup = (RadioGroup) convertView.findViewById(R.id.rdGroup);
holder.btnA = (RadioButton) convertView.findViewById(R.id.btnA);
holder.btnB = (RadioButton) convertView.findViewById(R.id.btnB);
holder.btnC = (RadioButton) convertView.findViewById(R.id.btnC);
holder.btnD = (RadioButton) convertView.findViewById(R.id.btnD);
holder.btnE = (RadioButton) convertView.findViewById(R.id.btnE);
holder.btnWhat = (Button) convertView.findViewById(R.id.btnWhat);
convertView.setTag(holder);
} else {
holder=(ViewHolder)convertView.getTag();
}
holder.rdGroup.setOnCheckedChangeListener(null);
holder.rdGroup.clearCheck();
Config.error("Spars "+mSpCheckedState.get(position));
if(mSpCheckedState.indexOfKey(position)>-1){
holder.rdGroup.check(mSpCheckedState.get(position));
}else{
holder.rdGroup.clearCheck();
}
holder.rdGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId>-1){
mSpCheckedState.put(position, checkedId);
}else{
if(mSpCheckedState.indexOfKey(position)>-1)
mSpCheckedState.removeAt(mSpCheckedState.indexOfKey(position));
}
}
});
Config.error("Current Position " + position);
holder.lblAnswerId.setText(position + 1 + "");
holder.btnWhat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.isSelected())
v.setSelected(false);
else
v.setSelected(true);
}
});
return convertView;
}
private static class ViewHolder {
private TextView lblAnswerId;
private RadioButton btnA;
private RadioButton btnB;
private RadioButton btnC;
private RadioButton btnD;
private RadioButton btnE;
private RadioGroup rdGroup;
private Button btnWhat;
}
void showToast(String text) {
if (t != null)
t.cancel();
t = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
t.show();
}
}

Issue with set the already checked to load and after again update

I am facing the problem to view the checked item of the listview and after if user want to modify the checked item to other item then he can modify check-box. After modify he again want to view what i checked in list. My code not working correct to view what he checked. Please help and it much appreciate
Here is my adapter class:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.kns.model.CategoryModel;
import com.sunil.selectmutiple.R;
public class CategoryAdapter extends BaseAdapter{
private final List<CategoryModel> list;
private final Activity context;
private LayoutInflater mInflater=null;
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
private static final String TAG="CategoryAdapter";
String catid1;
String catid2;
String catid3;
public CategoryAdapter(Activity context, List<CategoryModel> list, String catid1, String catid2, String catid3) {
// super(context, R.layout.listcheck, list);
mInflater = context.getLayoutInflater();
this.context = context;
this.list = list;
this.catid1=catid1;
this.catid2=catid2;
this.catid3=catid3;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int arg0) {
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = mInflater.inflate(R.layout.cate_list_item, parent, false);
}
CategoryModel p = getProduct(position);
TextView text = (TextView) view.findViewById(R.id.textView_custname);
CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkBox1);
checkbox.setOnCheckedChangeListener(myCheckChangList);
checkbox.setTag(position);
String catid=p.getCat_id();
Log.v(TAG, "Cat id is: "+catid);
Log.v(TAG, "Cat id1 is: "+catid1);
Log.v(TAG, "Cat id2 is: "+catid2);
Log.v(TAG, "Cat id3 is: "+catid3);
if (catid1.trim().equalsIgnoreCase("0") && catid2.trim().equalsIgnoreCase("0") && catid3.trim().equalsIgnoreCase("0")) {
checkbox.setChecked(p.isIsselected());
}
else{
if (catid.trim().equalsIgnoreCase(catid1)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid2)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else if (catid.trim().equalsIgnoreCase(catid3)) {
checkbox.setChecked(true);
// getProduct((Integer) checkbox.getTag()).setIsselected(true) ;
}
else{
checkbox.setChecked(false);
}
}
text.setText(p.getCat_name());
// checkbox.setChecked(p.isIsselected());
return view;
}
CategoryModel getProduct(int position) {
return ((CategoryModel) getItem(position));
}
public ArrayList<CategoryModel> getChecked() {
ArrayList<CategoryModel> list1 = new ArrayList<CategoryModel>();
for (CategoryModel details : list) {
if (details.isIsselected())
list1.add(details);
}
return list1;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ArrayList<CategoryModel> list1=getChecked();
Log.v(TAG, "checked size is: "+list1.size());
if (isChecked) {
if (list1.size() >= 3) {
buttonView.setChecked(false);
//getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
Toast.makeText(context, "Please select max 3 Categories.", Toast.LENGTH_LONG).show();
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
else{
getProduct((Integer) buttonView.getTag()).setIsselected(isChecked) ;
}
}
};
}

Categories

Resources