如何将 Map 值添加到 ArrayList 中?

How to add Map values into an ArrayList?

I want to add map values into an arraylist.This is my current code.

  ArrayList<Map<String, String>> itemData = new ArrayList<>();
    int index =0;

    Map<String, String> itemselected = new HashMap<>();
    itemselected.put("invoiceNo", textViewInvNo.getText().toString());//d
    itemselected.put("cstName", textViewCstName.getText().toString());//d
    itemselected.put("contact", textViewCstph.getText().toString());//d
    itemselected.put("barcode", barCode.getText().toString());//d
    itemselected.put("desc", itemDesc.getText().toString());//d
    itemselected.put("weight", weightLine.getText().toString());//d
    itemselected.put("rate", rateAmount.getText().toString());//d
    itemselected.put("makingAmt", makingAmount.getText().toString());//d
    itemselected.put("net_rate", netRate.getText().toString());//d
    itemselected.put("itemTotal", itemtotal.getText().toString());//d
    itemselected.put("vat", textViewVat.getText().toString());//d
    itemselected.put("sum_total", textViewSum.getText().toString());//d
    itemselected.put("bill_type", billType);//null

    itemData.add(index,itemselected);
    index++;

This is the output that i get.

[{rate=24000,weight=21.000,desc=item description,makingAmt=200,cstName=Test customer,sum_total=52094.46,vat=1021.46,itemTotal=51073,barcode=BQSP78BB,net_rate=24200,invoiceNo=1842,bill_type=estimate,contact=+91-8600931386}]

This is the output I am expecting.

[{rate=24000,weight=21.000,desc=item description,makingAmt=200,cstName=Test customer,sum_total=52094.46,vat=1021.46,itemTotal=51073,barcode=BQSP78BB,net_rate=24200,invoiceNo=1842,bill_type=estimate,contact=+91-8600931386},{rate=24000,weight=21.000,desc=item description,makingAmt=200,cstName=Test customer,sum_total=52094.46,vat=1021.46,itemTotal=51073,barcode=BQSP79BB,net_rate=24200,invoiceNo=1842,bill_type=estimate,contact=+91-8600931386}, {rate=24000,weight=21.000,desc=item description,makingAmt=200,cstName=Test customer,sum_total=52094.46,vat=1021.46,itemTotal=51073,barcode=BQSP80BB,net_rate=24200,invoiceNo=1842,bill_type=estimate,contact=+91-8600931386}]

I have a method called showItem() that contains itemTable().This is code for itemTable()

    private void itemTable(String itembarcode, String itemdesc, String weight, String rate, String making, String netrate, String total) {
    TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
    TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1f);
    rowParams.setMargins(16, 0, 16, 0);

    TableLayout tableLayout = new TableLayout(AddInvEst.this);
    tableLayout.setLayoutParams(tableParams);


    TableRow newRow = new TableRow(AddInvEst.this);
    newRow.setLayoutParams(tableParams);

    barCode = new TextView(AddInvEst.this);
    barCode.setLayoutParams(rowParams);
    barCode.setGravity(Gravity.CENTER);

    itemDesc = new TextView(AddInvEst.this);
    itemDesc.setLayoutParams(rowParams);
    itemDesc.setGravity(Gravity.CENTER);

    weightLine = new TextView(AddInvEst.this);
    weightLine.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 0.75f));
    weightLine.setGravity(Gravity.CENTER);

    rateAmount = new EditText(AddInvEst.this);
    rateAmount.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 0.5f));
    rateAmount.setGravity(Gravity.CENTER);
    rateAmount.setInputType(InputType.TYPE_CLASS_PHONE);
    //rateAmount.setSelection(rateAmount.getText().length());
    rateAmount.addTextChangedListener(rateTextWatcher);

    makingAmount = new EditText(AddInvEst.this);

    makingAmount.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 0.5f));
    makingAmount.setGravity(Gravity.CENTER);
    makingAmount.setInputType(InputType.TYPE_CLASS_PHONE);
    makingAmount.addTextChangedListener(mkAmountTextWatcher);

    netRate = new TextView(AddInvEst.this);
    netRate.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 0.5f));
    netRate.setGravity(Gravity.CENTER);
    netrates.add(netrate);

    itemtotal = new TextView(AddInvEst.this);
    itemtotal.setTag(count);
    itemtotal.setLayoutParams(rowParams);
    itemtotal.setGravity(Gravity.CENTER);
    Toast.makeText(AddInvEst.this, "item count is " + itemtotal.getTag(), Toast.LENGTH_SHORT).show();
    totals.add(total);
    itemtotal.addTextChangedListener(totalTextWatcher);

    double[] doubleList = new double[totals.size()];
    double sum = 0.0d;
    for (int i = 0; i < totals.size(); ++i) {
        doubleList[i] = Double.parseDouble(totals.get(i));
        sum += doubleList[i];
    }

    barCode.setText(itembarcode);
    itemDesc.setText(itemdesc);
    weightLine.setText(weight);
    rateAmount.setText(rate);
    makingAmount.setText(making);
    netRate.setText(netrate);
    itemtotal.setText(total);
    textViewSum.setText(sum * (0.02) + sum + "");//set total text to sum
    textViewVat.setText(sum * (0.02) + "");

    ArrayList<Map<String, String>> itemData = new ArrayList<>();
    int index =0;

    Map<String, String> itemselected = new HashMap<>();
    itemselected.put("invoiceNo", textViewInvNo.getText().toString());//d
    itemselected.put("cstName", textViewCstName.getText().toString());//d
    itemselected.put("contact", textViewCstph.getText().toString());//d
    itemselected.put("barcode", barCode.getText().toString());//d
    itemselected.put("desc", itemDesc.getText().toString());//d
    itemselected.put("weight", weightLine.getText().toString());//d
    itemselected.put("rate", rateAmount.getText().toString());//d
    itemselected.put("makingAmt", makingAmount.getText().toString());//d
    itemselected.put("net_rate", netRate.getText().toString());//d
    itemselected.put("itemTotal", itemtotal.getText().toString());//d
    itemselected.put("vat", textViewVat.getText().toString());//d
    itemselected.put("sum_total", textViewSum.getText().toString());//d
    itemselected.put("bill_type", billType);//null

    itemData.add(index,itemselected);
    index++;




    /*JSONObject jsonObject = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    try {
        Toast.makeText(AddInvEst.this, "here the count is : "+count, Toast.LENGTH_SHORT).show();

            jsonArray.put(count-1 ,itemselected);
        jsonObject.put("itemSelected", jsonArray);

    } catch (JSONException e) {
        e.printStackTrace();
    }*/

    newRow.addView(barCode);
    newRow.addView(itemDesc);
    newRow.addView(weightLine);
    newRow.addView(rateAmount);
    newRow.addView(makingAmount);
    newRow.addView(netRate);
    newRow.addView(itemtotal);
    itemTable.addView(newRow);

    TextView display = (TextView) findViewById(R.id.tv_display);
    display.setText(itemData.toString());

    Toast.makeText(AddInvEst.this, itemData.toString(), Toast.LENGTH_SHORT).show();


}

This code for showItem()

    private void showItem(String json) {
    String itembarcode = "";
    String itemdesc = "";
    String weight = "";
    String rate = "";
    String making = "";
    String netrate = "";
    String total = "";

    try {
        JSONObject jsonObject = new JSONObject(json);
        JSONArray result = jsonObject.getJSONArray(ParseBarcode.JSON_ARRAY);
        JSONObject itemData = result.getJSONObject(0);
        itembarcode = itemData.getString(ParseBarcode.KEY_BARCODE);
        itemdesc = itemData.getString(ParseBarcode.KEY_DESC);
        weight = itemData.getString(ParseBarcode.KEY_WEIGHT);
        rate = itemData.getString(ParseBarcode.KEY_RATE);
        making = itemData.getString(ParseBarcode.KEY_MAKING);
        netrate = itemData.getString(ParseBarcode.KEY_NETRATE);
        total = itemData.getString(ParseBarcode.KEY_TOTAL);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    //dynamic table generation code

    itemTable(itembarcode, itemdesc, weight, rate, making, netrate, total);
}

This is where I call showItem in the else block.

   private void sendBarcode(final String url, final String barcodeNo) {
    final Context context = getApplicationContext();
    //String url = ITEM_URL+barcodeNum+toString().trim();
    if (barcodeNo.equals("")) {
        Toast.makeText(AddInvEst.this, "Please enter a valid barcode number ", Toast.LENGTH_LONG).show();
    }
    loading = ProgressDialog.show(AddInvEst.this, "Please wait...", "Fetching...", false, false);

    StringRequest stringReq = new StringRequest(url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (response.equalsIgnoreCase("notfound")) {
                        final Dialog dialogCrash = new Dialog(AddInvEst.this);
                        dialogCrash.setContentView(R.layout.crashreport);
                        TextView crashreport = (TextView) dialogCrash.findViewById(R.id.tv_crashcode);
                        crashreport.setText("Please Enter a valid Barcode Number ...");

                        Button bt_crash = (Button) dialogCrash.findViewById(R.id.bt_crash);
                        bt_crash.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialogCrash.dismiss();
                            }
                        });

                        dialogCrash.show();
                        loading.dismiss();

                    } else {

                        loading.dismiss();
                        showItem(response);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, "Your Internet connection is slow or not available!", Toast.LENGTH_SHORT).show();
                    loading.dismiss();
                }
            });
    RequestQueue reqQueue = Volley.newRequestQueue(context);
    reqQueue.add(stringReq);
}

And sendBarcode is what I call onClick of a button.

class A {
    List<Map<String,String>> itemData;

    public A() {
        itemData = new ArrayList<>();
    }

    private void itemTable {
         ...
        int index =0;

        Map<String, String> itemselected = new HashMap<>();
        itemselected.put("invoiceNo", textViewInvNo.getText().toString());//d
        itemselected.put("cstName", textViewCstName.getText().toString());//d
        itemselected.put("contact", textViewCstph.getText().toString());//d
        itemselected.put("barcode", barCode.getText().toString());//d
        itemselected.put("desc", itemDesc.getText().toString());//d
        itemselected.put("weight", weightLine.getText().toString());//d
        itemselected.put("rate", rateAmount.getText().toString());//d
        itemselected.put("makingAmt", makingAmount.getText().toString());//d
        itemselected.put("net_rate", netRate.getText().toString());//d
        itemselected.put("itemTotal", itemtotal.getText().toString());//d
        itemselected.put("vat", textViewVat.getText().toString());//d
        itemselected.put("sum_total", textViewSum.getText().toString());//d
        itemselected.put("bill_type", billType);//null

        itemData.add(index,itemselected);
        index++;

         ...
    }
}

好吧,如果你认为以结果为导向,为了你想要的,你可以通过拥有自己的项目 class 使整个过程变得非常容易。这将减少您在 UI 线程上的编码。

制作classItem.java

包 day.eight;

public class Item {

    private int rate = 0;
    private int weight = 0;
    private String desc = null;
    private int makingAmt = 0;
    private String cstName = null;
    private float sum_total = 0;
    private float vat = 0;
    private int itemTotal = 0;
    private String barcode = null;
    private int net_rate = 0;
    private int invoiceNo = 0;
    private String bill_type = null;
    private String contact = null;

    public int getRate() {
        return rate;
    }
    public void setRate(int rate) {
        this.rate = rate;
    }
    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public int getMakingAmt() {
        return makingAmt;
    }
    public void setMakingAmt(int makingAmt) {
        this.makingAmt = makingAmt;
    }
    public String getCstName() {
        return cstName;
    }
    public void setCstName(String cstName) {
        this.cstName = cstName;
    }
    public float getSum_total() {
        return sum_total;
    }
    public void setSum_total(float sum_total) {
        this.sum_total = sum_total;
    }
    public float getVat() {
        return vat;
    }
    public void setVat(float vat) {
        this.vat = vat;
    }
    public int getItemTotal() {
        return itemTotal;
    }
    public void setItemTotal(int itemTotal) {
        this.itemTotal = itemTotal;
    }
    public String getBarcode() {
        return barcode;
    }
    public void setBarcode(String barcode) {
        this.barcode = barcode;
    }
    public int getNet_rate() {
        return net_rate;
    }
    public void setNet_rate(int net_rate) {
        this.net_rate = net_rate;
    }
    public int getInvoiceNo() {
        return invoiceNo;
    }
    public void setInvoiceNo(int invoiceNo) {
        this.invoiceNo = invoiceNo;
    }
    public String getBill_type() {
        return bill_type;
    }
    public void setBill_type(String bill_type) {
        this.bill_type = bill_type;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
}

现在您已经拥有项目所需的所有属性 object 是时候对其进行测试了,

我的意思是,我们将只检查我们是否可以创建它的对象并制作所需的 JSON 字符串并尝试从我们将创建的 JSON 中退出 Object

以下代码只是制作所需 JSON 数据的测试代码,这取决于您希望如何在生产环境中创建数据

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ItemTestDrive {

    public static void main(String[] args) {

        ArrayList<Item> items = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            Item item = new Item();
            item.setRate(248 + i);
            item.setWeight(21 + i);
            item.setDesc("itemdescription: " + i);
            item.setMakingAmt(200 + i);
            item.setCstName("Testcustomer: " + i);
            item.setSum_total((float) (52094.46 + i));
            item.setVat((float) 1021.46 + i);
            item.setItemTotal(200);
            item.setBarcode("BQSP78BB" + i);
            item.setNet_rate(2450 + i);
            item.setInvoiceNo(1845 + i);
            item.setBill_type("estimate: +i");
            item.setContact("+91-8600931386");
            items.add(item);
        }

        /**
         * This code will convert your ArrayList object to a equivalent JSON
         * String
         */
        String result = (new Gson()).toJson(items);
        System.out.println("" + result);

        /**
         * This code will convert your JSON String to a equivalent ArrayList
         * Object
         */
        ArrayList<Item> items2 = (new Gson()).fromJson(result,new TypeToken<ArrayList<Item>>() {}.getType());
    }
}

Output

[
  {
    "rate": 248,
    "weight": 21,
    "desc": "itemdescription: 0",
    "makingAmt": 200,
    "cstName": "Testcustomer: 0",
    "sum_total": 52094.46,
    "vat": 1021.46,
    "itemTotal": 200,
    "barcode": "BQSP78BB0",
    "net_rate": 2450,
    "invoiceNo": 1845,
    "bill_type": "estimate: +i",
    "contact": "+91-8600931386"
  },
  {
    "rate": 249,
    "weight": 22,
    "desc": "itemdescription: 1",
    "makingAmt": 201,
    "cstName": "Testcustomer: 1",
    "sum_total": 52095.46,
    "vat": 1022.46,
    "itemTotal": 200,
    "barcode": "BQSP78BB1",
    "net_rate": 2451,
    "invoiceNo": 1846,
    "bill_type": "estimate: +i",
    "contact": "+91-8600931386"
  },
  {
    "rate": 250,
    "weight": 23,
    "desc": "itemdescription: 2",
    "makingAmt": 202,
    "cstName": "Testcustomer: 2",
    "sum_total": 52096.46,
    "vat": 1023.46,
    "itemTotal": 200,
    "barcode": "BQSP78BB2",
    "net_rate": 2452,
    "invoiceNo": 1847,
    "bill_type": "estimate: +i",
    "contact": "+91-8600931386"
  }
]