Android Studio: добавление новой группы / дочернего элемента в ExpandableListView портится с предыдущей - PullRequest
0 голосов
/ 20 марта 2019

Я добавляю новые группы и child без проблем в ExpandableListView, но child предыдущей группы всегда изменяется при добавлении новой группы / child .

На картинке ниже я добавил группу = DOНОЛЬ и дочерний = 123 .

addProd1

Теперь, когда я добавляю новый группа = ФИНАЛ CORRECAO и child = 987 , дочерний элемент предыдущей группы ( DO ZERO ) также получаетизменено.

addProd2

Я не знаю, почему это происходит.

Вот как я реализовал объект.

public class ExpandableObjectc {

    private String groupName;
    private ArrayList<ProductObject> productList;

    public ExpandableObjectc(String groupName, ArrayList<ProductObject> productList) {
        this.groupName = groupName;
        this.productList = productList;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public ArrayList<ProductObject> getProductList() {
        return productList;
    }

    public void setProductList(ArrayList<ProductObject> productList) {
        this.productList = productList;
    }
}

Вот как я реализовал адаптер

public class ExpandableAdapterc extends BaseExpandableListAdapter {

    private Context context;
    private ArrayList<ExpandableObjectc> groupList;
    private ArrayList<ExpandableObjectc> groupListFull;

    public ArrayList<ExpandableObjectc> getMParent() {
        return groupList;
    }

    public ExpandableAdapterc(Context context, ArrayList<ExpandableObjectc> groupList) {
        this.context = context;
        this.groupList = groupList;
        this.groupListFull = new ArrayList<>(groupList);
    }

    @Override
    public int getGroupCount() {
        return groupList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        ArrayList<ProductObject> productList = groupList.get(groupPosition).getProductList();
        return productList.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groupList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        ArrayList<ProductObject> productList = groupList.get(groupPosition).getProductList();
        return productList.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ExpandableObjectc group = (ExpandableObjectc) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.expandable_group, null);
        }

        TextView mGroupName = (TextView) convertView.findViewById(R.id.expandable_groupName);
        //ImageView mArrow = (ImageView) convertView.findViewById(R.id.expandable_arrow);

        mGroupName.setText(group.getGroupName());

        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ProductObject product = (ProductObject) getChild(groupPosition, childPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.item_product, null);
        }

        CircleImageView mImage = (CircleImageView) convertView.findViewById(R.id.item_productImage);
        TextView mCode = (TextView) convertView.findViewById(R.id.item_productCode);
        TextView mAmount = (TextView) convertView.findViewById(R.id.item_productAmount);
        TextView mPrice = (TextView) convertView.findViewById(R.id.item_productPrice);
        TextView mDescription = (TextView) convertView.findViewById(R.id.item_productDescription);
        ImageButton mProductDelete = (ImageButton) convertView.findViewById(R.id.item_productDelete);
        ImageButton mProductEdit = (ImageButton) convertView.findViewById(R.id.item_productEdit);
        ToggleButton mFavorite = (ToggleButton) convertView.findViewById(R.id.item_productFavorite);

        if (product.getImage() != null) {
            byte[] prodIMG = product.getImage();
            Bitmap bitmap = BitmapFactory.decodeByteArray(prodIMG,0,prodIMG.length);
            mImage.setImageBitmap(bitmap);
            //Log.i("debinf prodadapter", "Private Image != null for "+productList.get(position).getDescription());
        } else {
            mImage.setImageResource(R.drawable.shopping_cart_black_48dp);
        }

        mCode.setText(product.getCode());
        mAmount.setText(product.getAmount());
        mPrice.setText(product.getPrice());
        mDescription.setText(product.getDescription());

        mProductDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeChildFromGroup(groupPosition, childPosition);
            }
        });

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public void removeChildFromGroup(int groupPosition, int childPosition) {
        ExpandableObjectc group = (ExpandableObjectc) getGroup(groupPosition);
        group.getProductList().remove(childPosition);

        notifyDataSetChanged();
    }

    public void filterData(String query) {
        query = query.toLowerCase();
        groupList.clear();

        if (query.isEmpty()) {
            groupList.addAll(groupListFull);
        } else {
            for (ExpandableObjectc group : groupListFull) {
                ArrayList<ProductObject> productList = group.getProductList();
                ArrayList<ProductObject> newList = new ArrayList<>();
                for (ProductObject product : productList) {
                    if (product.getCode().toLowerCase().contains(query) || product.getDescription().toLowerCase().contains(query)) {
                        newList.add(product);
                    }
                }
                if (newList.size() > 0) {
                    ExpandableObjectc nGroup = new ExpandableObjectc(group.getGroupName(), newList);
                    groupList.add(nGroup);
                }
            }
        }
        notifyDataSetChanged();
    }
}

А вот как я добавляю новую группу / child в MainActivity, гдеgroupName взято из spinner, показанного на первом изображении выше.

private void writeProductOnDisk(String groupName) {
        boolean isGroup = false;

        ProductObject productObject = new ProductObject(imageViewToByte(mProductImage), mCode.getText().toString(), mAmount.getText().toString(), mPrice.getText().toString(), mDescription.getText().toString(),false);

        for (int i = 0; i < dataForExpandable.size(); i++) {
            if (groupName.equals(dataForExpandable.get(i).getGroupName())) {
                dataForExpandable.get(i).getProductList().add(productObject);
                isGroup = true;
                mProductListAdapter.notifyDataSetChanged();
                Log.i("debinf prodact", "groupName already exists "+ groupName);
                break;
            }
        }

        if (!isGroup) {
            productList.clear();
            productList.add(productObject);
            dataForExpandable.add(new ExpandableObjectc(groupName,productList));
            mProductListAdapter.notifyDataSetChanged();
            Log.i("debinf prodact", "groupName DO NOT exists, creating new one "+ groupName);
        }
    }

Я не знаю, возникает ли проблема в ADApter или когда я добавляю новый element в переменную dataForExpandable.

Я ценю любую помощь!

РЕДАКТИРОВАТЬ

Я добавилцикл после добавления новой группы / child , чтобы напечатать то, что было внутри переменной dataForExpandable, и я вижу, что проблема, вероятно, возникает в методе добавления dataForExpandable.add(new ExpandableObjectc(groupName,productList));, потому что этокажется, что он переопределяет предыдущую группу / child новой.

Он переопределяет все продукты, которые я вставил groupName = Grupo Diamante с новым ребенком, которого я добавил в groupName = boa gatolino .

debinf prodact: groupName DO NOT exists, creating new one boa gatolino
debinf prodact: groupName is DO ZERO product is 123
debinf prodact: groupName is CORRECAO FINAL product is 987
debinf prodact: groupName is CORRECAO FINAL product is 111
debinf prodact: groupName is CORRECAO FINAL product is 223
debinf prodact: groupName is CORRECAO FINAL product is 741
debinf prodact: groupName is PARECE QUE AGORA FOI product is 555
debinf prodact: groupName is PARECE QUE AGORA FOI product is 369
debinf prodact: groupName is Grupo Diamante product is 357
debinf prodact: groupName is boa gatolino product is 357

Какой лучший способ добавить новую группу / ребенок

1 Ответ

1 голос
/ 23 марта 2019

Вместо добавления элемента в dataForExpandable (Activity) / groupList (Adapter) может быть лучше добавить элемент в groupListFull (Adapter) и вызвать filterData() для обновления groupList . Поэтому попробуйте следующее:

Добавьте эти методы внутри адаптера:

public int getBackingListGroupCount() {
    return groupListFull.size();
}

public ExpandableObjectc getBackingListGroup(int groupPosition) {
    return groupListFull.get(groupPosition);
}

public void addBackingListGroup(ExpandableObjectc group) {
    groupListFull.add(group);
}

Изменения в активности:

private void writeProductOnDisk(String groupName) {
    boolean isGroup = false;

    SearchView searchView = findViewById(R.id.SearchView);

    ProductObject productObject = new ProductObject(imageViewToByte(mProductImage), mCode.getText().toString(), mAmount.getText().toString(), mPrice.getText().toString(), mDescription.getText().toString(),false);

    for (int i = 0; i < mProductListAdapter.getBackingListGroupCount(); i++) {
        if (groupName.equals(mProductListAdapter.getBackingListGroup(i).getGroupName())) {
            mProductListAdapter.getBackingListGroup(i).getProductList().add(productObject);
            isGroup = true;
            mProductListAdapter.filterData(searchView.getQuery().toString());
            Log.i("debinf prodact", "groupName already exists "+ groupName);
            break;
        }
    }

    if (!isGroup) {
        productList = new ArrayList<>();
        productList.add(productObject);
        mProductListAdapter.addBackingListGroup(new ExpandableObjectc(groupName,productList));
        mProductListAdapter.filterData(searchView.getQuery().toString());
        Log.i("debinf prodact", "groupName DO NOT exists, creating new one "+ groupName);
    }
}

Надеюсь, это поможет!

...