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

时间:2018-12-31 04:00:43

标签: java android arrays json

我正在尝试制作衣物订购应用程序。我已经完成了订购过程,在订购过程结束时,用户单击了下一个按钮以签出订购的结果,我已经成功地签出了签出结果,但是我所做的仍然在一个可变字符串中。如何将结帐结果放入数组变量中,以便我可以将结果以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发布到服务器?请帮我解决这个问题。因为我还是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;
}

}

3 个答案:

答案 0 :(得分: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;
    }
}

创建另一个要在arraylist中添加的变量的Getter setter类

OrderItem:-

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

答案 1 :(得分:0)

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

据我所知,这应该解决:

    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” ..使用它来做您需要做的一切。

答案 2 :(得分:0)

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

grepl("evet", test$hashtags)
#[1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE