java - 如何将一些数据放入数组变量并作为 JSONarray 发布?

标签 java android arrays json

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

这是我的订单 Activity 代码:

@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 发布到服务器?请帮我解决这个问题。因为我还是 android 的初学者。

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

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;
}

}

最佳答案

只需创建 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
        }
        ]
}

关于java - 如何将一些数据放入数组变量并作为 JSONarray 发布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983464/

相关文章:

java - 将 JSONObject 转换为 Java 对象

android - React Native - 如何从 componentWillReceiveProps 重定向到登录 View

javascript - 如何将字符串对象从套接字转换为Javascript中的键值对并显示在html上

java智能日期解析器

java - EclipseLink - 在元模型中未找到关键类 [CurriculumTree] 的 [EntityType]

android - 使用当前汇率在 Android 中将 INR 转换为美元货币?

c - C中用指针初始化数组

javascript正则表达式匹配仅返回最后一个匹配

java - 这不可能获取类名并在类内设置变量吗?

Android - 让 ImageView 适合 ListView