Search code examples
androidstringandroid-recyclerviewstringbuilder

How to create a custom string and populate it dynamically?


I'm making an app that can add from button click some items to a recyclerView formatted as "name / quantity / price" and after i click a button called "Print" it's save my StringBuilder made from different items added to recyclerView and send it via FTP to a printer.

For now it's working right but i have now to add swipe to delete to the recyclerView and i'll have problems with deleting StringBuilder that corresponds to the exact item from the recyclerView.

Do you have any suggestion on how can i do to make that custom string by adding items to the recyclerView and on swipe delete also the corresponding string?

Here is my onClick method where i add the items to the recyclerView and also add the items to the stringBuilder "scontrino" that have to be formatted as you can see on the method with all that "" etc...

    mAdapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onItemClick(final int position) {

            double prezzoScont;

            itemCassas.add(new ItemCassa(filteredList.get(position).getDeskS(),filteredList.get(position).getQuant(),filteredList.get(position).getPrice()));


                prezzo = (prezzo + (filteredList.get(position).getPrice()));


            scontrino
                    .append("<SELLITEM>").append("\n")
                    .append("<DESCRIPTION>").append(filteredList.get(position).getDeskS()).append("</DESCRIPTION>").append("\n")
                    .append("<QUANTITY>").append(filteredList.get(position).getQuant()).append("</QUANTITY>").append("\n")
                    .append("<PRICE>").append(new DecimalFormat("#0.00").format(filteredList.get(position).getPrice())).append("</PRICE>").append("\n")
                    .append("</SELLITEM>").append("\n");


            price.setText(String.valueOf(new DecimalFormat("#0.00").format(prezzo)));
            exampleAdapter.notifyItemInserted(itemCassas.size());
            mRecyclerViewTOP.scrollToPosition(itemCassas.size() - 1);

        }
    });

Here is a screenshot of what's happening in my app

screenshot


Solution

  • I think we can resolve your issue by the way using a list, instead of StringBuilder

    first, assume we have 3 string like ""name","quantity","price"

    so we create List

    List<String> list = new ArrayList<>();
            list.add("name");
            list.add("quantity");
            list.add("price");
    

    whenever you want remove any item (by swipe)

    list.remove("quantity");
    

    and finally, when you want print the result

    StringBuilder result = new StringBuilder();
    
        for (String s : list) {
            result.append(s);
        }
    

    hope this helps