【问题标题】:how to put a few data into array variable and post as JSONarray?如何将一些数据放入数组变量并作为 JSONarray 发布?
【发布时间】:2026-02-01 04:05:02
【问题描述】:

我正在尝试制作一个洗衣订购应用程序。我已经到了下单流程,在下单流程结束时,用户点击下一步按钮来结账下单的结果,我已经成功做出结账结果,但是我做的还是在一个变量字符串中。如何将结帐结果放入数组变量中,以便我可以将结果以 JSONArray 的形式发布?

这是我的订单活动代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_produk);

    // menghubungkan variablel pada layout dan pada java
    listProduk   = (ListView)findViewById(R.id.list_produk);
    swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
    radioExpress = (RadioButton)findViewById(R.id.radio_express);
    radioReguler = (RadioButton)findViewById(R.id.radio_regular);
    tvTotal      = (TextView)findViewById(R.id.total);
    next         = (Button)findViewById(R.id.button_next);
    actionBar    = getSupportActionBar();

    laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);

    // untuk mengisi data dari JSON ke dalam adapter
    productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
    listProduk.setAdapter(productAdapter);
    listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            productAdapter.setCheckBox(position);

        }
    });

    // menampilkan widget refresh
    swipeProduct.setOnRefreshListener(this);

    swipeProduct.post(new Runnable() {
                   @Override
                   public void run() {
                       swipeProduct.setRefreshing(true);
                       productList.clear();
                       tvTotal.setText(String.valueOf(0));
                       radioReguler.isChecked();
                       regular = true;
                       productAdapter.notifyDataSetChanged();
                       callProduct();
                   }
               }
    );

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String checkbox = "";
            for (ProductModel hold : productAdapter.getAllData()) {
                int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
                if (hold.isCheckbox()) {
                    checkbox += "\n" + hold.getProduct_name() + " " + total;
                }
            }
            if (!checkbox.isEmpty()) {
                dipilih = checkbox;
            } else {
                dipilih = "Anda Belum Memilih Menu.";
            }

            formSubmit(dipilih);
        }
    });

}

private void formSubmit(String hasil){
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    LayoutInflater inflater = getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.form_submit, null);
    dialog.setView(dialogView);
    dialog.setIcon(R.mipmap.ic_launcher);
    dialog.setTitle("Menu Yang Dipilih");
    dialog.setCancelable(true);

    txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);

    txtnamaProduk.setText(hasil);

    dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    dialog.show();
}

这是结果代码:

next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String checkbox = "";
            for (ProductModel hold : productAdapter.getAllData()) {
                int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
                if (hold.isCheckbox()) {
                    checkbox += "\n" + hold.getProduct_name() + " " + total;
                }
            }
            if (!checkbox.isEmpty()) {
                dipilih = checkbox;
            } else {
                dipilih = "Anda Belum Memilih Menu.";
            }

            formSubmit(dipilih);
        }
    });

}

在我上面的代码中,我仍然使用变量复选框来容纳用户选择的订单的所有结果。如何将所有结果放入数组变量中,以便我可以作为 JSONArray 发布到服务器?请帮我解决这个问题。因为我还是安卓的初学者。

如果需要,这是我的适配器代码:

public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;

public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
    this.context      = context;
    this.productItems  = items;
    this.produk        = produk;
}


@Override
public int getItemViewType(int position) {

    return position;
}

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

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

@Override
public long getItemId(int position) {
    return 0;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
    final ViewHolder viewHolder;
    final ProductModel items = productItems.get(position);

    if(view == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view                  = inflater.inflate(R.layout.list_produk, null, true);
        viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
        viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
        viewHolder.count    = (TextView) view.findViewById(R.id.count_product);
        viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
        viewHolder.price    = (TextView) view.findViewById(R.id.product_price);
        view.setTag(viewHolder);
    }else{
        viewHolder = (ViewHolder) view.getTag();
    }
    viewHolder.checkBox.setText(items.getProduct_name());
    viewHolder.price.setText(items.getProduct_price());
    viewHolder.count.setText(String.valueOf(items.getCountProduct()));

    //fungsi untuk set posisi textview + dan -
    viewHolder.increase.setTag(R.integer.btn_plus_view, view);
    viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
    viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
    viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);

    //fungsi untuk disable textview + dan - jika checkbox tidak di klik
    viewHolder.decrease.setOnClickListener(null);
    viewHolder.increase.setOnClickListener(null);

    if(items.isCheckbox()){
        viewHolder.checkBox.setChecked(true);
        viewHolder.increase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
                TextView tv   = (TextView) tempview.findViewById(R.id.count_product);
                Integer pos   = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);

                int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
                tv.setText(String.valueOf(countProduct));
                productItems.get(pos).setCountProduct(countProduct);
                produk.tambah(pos);
            }
        });
        viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
                TextView tv   = (TextView) tempview.findViewById(R.id.count_product);
                Integer pos   = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);

                int total = productItems.get(pos).getCountProduct();
                if (total>0){
                    int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
                    tv.setText(String.valueOf(countProduct));
                    productItems.get(pos).setCountProduct(countProduct);
                    produk.kurang(pos);
                }
            }
        });
    } else {
        viewHolder.checkBox.setChecked(false);

        //fungsi untuk reset jumlah harga dan produk pada checkbox
        String count = viewHolder.count.getText().toString();
        int jumlah = Integer.parseInt(count);
        int harga  = Integer.parseInt(productItems.get(position).getProduct_price());
        int kurang = jumlah * harga;
        viewHolder.count.setText("0");
        productItems.get(position).setCountProduct(0);
        produk.kurangCheckbox(kurang);
    }

    return view;
}

public ArrayList<ProductModel> getAllData(){
    return productItems;
}

public void setCheckBox(int position){
    ProductModel items = productItems.get(position);
    items.setCheckbox(!items.isCheckbox());
    notifyDataSetChanged();
}

static class ViewHolder{
    TextView decrease, count, increase, price;
    CheckBox checkBox;
}

}

【问题讨论】:

  • 你尝试过哪些与创建 json 数组相关的事情?

标签: java android arrays json


【解决方案1】:

只需创建 Arraylist 的 getter setter 方法,如下所示

完成订单:-

public class CompleteOrder {

List<OrderItem> order_items;

 public List<OrderItem> getOrder_items() {
        return order_items;
    }

    public void setOrder_items(List<OrderItem> order_items) {
        this.order_items = order_items;
    }
}

创建另一个要添加到数组列表中的 Getter setter 类变量

订单项:-

public class OrderItem {
    String product_name;
    int product_total;

public OrderItem(String product_name, int product_total) {
        this.product_name = product_name;
        this.product_total = product_total;
    }

      public String getProduct_name() {
            return product_name;
        }

        public void setProduct_name(String product_name) {
            this.product_name = product_name;
        }

        public int getProduct_total() {
            return product_total;
        }

        public void setProduct_total(int product_total) {
            this.product_total = product_total;
        }
    }

现在在您的 onClick 方法中创建新的列表,如下所示

  public void onClick(View view) {

     String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
    List<OrderItem> masterProductorderCount=new ArrayList<>();
    for (ProductModel hold : productAdapter.getAllData()) {
                int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
                if (hold.isCheckbox()) {
                    checkbox += "\n" + hold.getProduct_name() + " " + total;

                    masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);

                }

            }
completeOrder.setOrder_items(masterProductorderCount);
     if (!checkbox.isEmpty()) {
                dipilih = checkbox;
            } else {
                dipilih = "Anda Belum Memilih Menu.";
            }

            formSubmit(completeOrder);//pass object of CompleteOrder
        }
     });

CompleteOrder 对象给出如下 JSON 输出

{
"CompleteOrder":[
        {
                "product_name":"your product name",
                "product_total":1
        },
            {
                "product_name":"your product name",
                "product_total":1
        },
        {
                "product_name":"your product name",
                "product_total":1
        }
        ]
}

【讨论】:

  • 你好 mittal varsani,我已经关注了您的代码,但是当我尝试在服务器端获取每行的值并将其插入数据库 mysql 时,我有点困惑。你能给我一个示例代码来从 API 文件中获取数组的值吗?我现在正在使用 volley 库来处理来自 API 的数据
【解决方案2】:

制作一个包含产品名称、总数等的模型, 然后将每个数据放入一个对象中,并将每个对象放入一个数组中 最后使用Gson 将属性映射到模型/模型列表或其他方式。

ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
    int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
    if (hold.isCheckbox()) {
        Model model = new Model();
        model.productName = hold.getProduct_name();
        model.total = total;

        list.add(model);
    }
}
String jsonArray = Gson().toJson(list);

【讨论】:

    【解决方案3】:

    您需要为JSONArray 中的每个条目创建一个JSONObject

    据我所知,这应该解决它:

        public void onClick(View view) {
            String checkbox = "";
            JSONArray jsonArray = new JSONArray();
            for (ProductModel hold : productAdapter.getAllData()) {
                int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
                if (hold.isCheckbox()) {
                    checkbox += "\n" + hold.getProduct_name() + " " + total;
    
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("product_name", hold.getProduct_name());
                    jsonObj.put("product_total", total);
                    jsonArray.put(jsonObj);
                }
            }
            if (!checkbox.isEmpty()) {
                dipilih = checkbox;
            } else {
                dipilih = "Anda Belum Memilih Menu.";
            }
    
            String jsonArrayString = jsonArray.toString();
            formSubmit(dipilih);
        }
    

    根据您的数据,jsonArrayString 的结果字符串将是:

    {[
    {"product_name":"product1","product_total":1},
    {"product_name":"product2","product_total":2},
    {"product_name":"product3","product_total":3}
    ]}
    

    我真的不知道你打算用 JSON 数据做什么,所以我只是创建了一个 String"jsonArrayString".. 用它做任何你需要做的事情。

    【讨论】:

    • 你好谷仓,你能告诉我输出的 jsonArray 吗?
    最近更新 更多