jeudi 6 juillet 2017

Checkbox state changes in custom Listview when onTextChangelistener in used for searching through the Listview

I am trying to get all the checked rows into an ArrayList to transfer them to the next activity but whenever I check some row and try searching for another row, the previous checked state changes to an unchecked state automatically. I would like to know how to solve this issue.

checked a product

When search option is used the checked status changes

This is my Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:app="http://ift.tt/GEGVYd"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" tools:context="hmbrsalesapp.androidstudio.com.hmbrsalesapp.OrderPlacementProduct">

<EditText
    android:id="@+id/OrderSearchProductId"
    android:clickable="true"
    android:hint="Search Products"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

<ListView
    android:id="@+id/OrderProductListViewId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/ProcessOrderButton"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:listSelector="@drawable/list_selector"
    android:divider="#000000"
    android:dividerHeight="1dp"/>

<Button
    android:id="@+id/ProcessOrderButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/OrderSearchProductId"
    android:text="Process Order"/>
</RelativeLayout>

this is the Activity_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_selector"
android:padding="5dp">

<TextView
    android:id="@+id/productCodeId"
    android:text="1122"
    android:textSize="20sp"
    android:textStyle="bold"
    android:textColor="#000000"
    android:paddingLeft="5dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignLeft="@+id/productNameid"
    android:layout_alignStart="@+id/productNameid" />

<TextView
    android:id="@+id/productNameid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxWidth="200dp"
    android:text="Korean Putty"
    android:textSize="20sp"
    android:textStyle="bold"
    android:textColor="#000000"
    android:paddingLeft="5dp"
    android:paddingTop="5dp"
    android:layout_below="@+id/productCodeId"
    android:layout_toRightOf="@+id/productCheckbox"
    android:layout_toEndOf="@+id/productCheckbox" />

<CheckBox
    android:id="@+id/productCheckbox"
    android:paddingRight="5dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:id="@+id/quantityId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:textSize="30dp"
    android:hint="Qty"
    android:textColor="#000000"
    android:layout_marginRight="11dp"
    android:layout_marginEnd="11dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
 </RelativeLayout>

My main Activity.java

public class OrderPlacementProduct extends AppCompatActivity {
private EditText productInfoSearchEdit;
private Button confirmOrderButton;
private ListView productInfoListView;
private OrderViewAdapter orderViewAdapter;

private DatabaseHandler dba;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_order_placement_product);
    getSupportActionBar().setTitle("Choose Product");
    String businessIdStr = null;

    productInfoSearchEdit = (EditText)findViewById(R.id.OrderSearchProductId);
    confirmOrderButton = (Button) findViewById(R.id.ProcessOrderButton);
    productInfoListView = (ListView) findViewById(R.id.OrderProductListViewId);

    dba = new DatabaseHandler(getApplicationContext());

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        businessIdStr = extras.getString("zid");
    }

    final ArrayList<HashMap<String,String>> prodInfoMapArray = dba.getProducts(businessIdStr);
    final ArrayList<HashMap<String,String>> tempItemInfo = new ArrayList<HashMap<String, String>>(prodInfoMapArray);

    orderViewAdapter = new OrderViewAdapter(getApplicationContext(),prodInfoMapArray);
    productInfoListView.setAdapter(orderViewAdapter);

    productInfoSearchEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String searchStringTotal = productInfoSearchEdit.getText().toString();
            int textLength = searchStringTotal.length();
            tempItemInfo.clear();

            if (s != null && s.length() > 0){
                for (int i = 0; i < prodInfoMapArray.size(); i++){
                    String productCode = prodInfoMapArray.get(i).get("xitem").toString();
                    String productName = prodInfoMapArray.get(i).get("xdesc").toString(); //create seperate strings and add them together so that contains works for all the components of the specific cusInfoMapArray object


                    String customerName = productCode + " " + productName;
                    if (textLength <= customerName.length()){
                        if (containsIgnoreCase(customerName,searchStringTotal)){
                            tempItemInfo.add(prodInfoMapArray.get(i));
                            orderViewAdapter = new OrderViewAdapter(getApplicationContext(),tempItemInfo);
                            productInfoListView.setAdapter(orderViewAdapter);
                        }
                    }
                }
            }else{
                orderViewAdapter = new OrderViewAdapter(getApplicationContext(),prodInfoMapArray);
                productInfoListView.setAdapter(orderViewAdapter);
            }

            orderViewAdapter.notifyDataSetChanged();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

public static boolean containsIgnoreCase(String str, String searchStr){
    if (str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--){
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }

    return false;
}
}

and finally the Custom ListView Adapter

public class OrderViewAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<HashMap<String,String>> itemInfo;
private static LayoutInflater listInflator = null;
private SparseBooleanArray selectedProducts;


public OrderViewAdapter(Context consContext, ArrayList<HashMap<String,String>> data ){
    mContext = consContext;
    itemInfo = data;
    listInflator = (LayoutInflater) consContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    selectedProducts = new SparseBooleanArray(itemInfo.size());
}

@Override
public int getCount() {
    return itemInfo.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

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

    View itemView = convertView;


    if (convertView == null) {
        itemView = listInflator.inflate(R.layout.activity_order_placement_product_list_row, null);
    }


    TextView productCode = (TextView) itemView.findViewById(R.id.productCodeId);
    TextView productName = (TextView) itemView.findViewById(R.id.productNameid);
    final CheckBox selectedCheck = (CheckBox) itemView.findViewById(R.id.productCheckbox);
    EditText quantityOrdered = (EditText) itemView.findViewById(R.id.quantityId);

    final HashMap<String, String> mItemInfo = itemInfo.get(position);

    quantityOrdered.setFocusable(true);
    quantityOrdered.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus){
                final int position = v.getId();
                final EditText quantity = (EditText) v;
                mItemInfo.put("qty",quantity.getText().toString());
                notifyDataSetChanged();
            }
        }
    });

    productCode.setText(mItemInfo.get("xitem"));
    productName.setText(mItemInfo.get("xdesc"));
    quantityOrdered.setText(mItemInfo.get("qty"));

    selectedCheck.setTag(position);
    selectedCheck.setChecked(selectedProducts.get(position,false));

    selectedCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int getPosition = (Integer) buttonView.getTag();
            selectedProducts.put(getPosition,isChecked);
        }
    });

    return itemView;
}

public boolean isChecked(int position){
    return selectedProducts.get(position,false);
}

public void setChecked(int position, boolean isChecked){
    selectedProducts.put(position,isChecked);
    notifyDataSetChanged();
}

public void toggle(int position){
    setChecked(position,!isChecked(position));
}
}

Also, this is my first time posting on S.O so if there are any problems with the way I phrased my problem or the way in which I presented my code please let me know.




Aucun commentaire:

Enregistrer un commentaire