/app/src/main/java/com/android/chefmonster/Checkout/Checkout.java
https://gitlab.com/santoshvarma4u/chefmonster-Android · Java · 883 lines · 668 code · 162 blank · 53 comment · 58 complexity · 5276284d77e824a476698280f5af8beb MD5 · raw file
- package com.android.chefmonster.Checkout;
- import android.app.ProgressDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.support.annotation.NonNull;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.DefaultItemAnimator;
- import android.support.v7.widget.LinearLayoutManager;
- import android.support.v7.widget.RecyclerView;
- import android.support.v7.widget.Toolbar;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.view.inputmethod.InputMethodManager;
- import android.widget.ArrayAdapter;
- import android.widget.AutoCompleteTextView;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.RelativeLayout;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.afollestad.materialdialogs.DialogAction;
- import com.afollestad.materialdialogs.MaterialDialog;
- import com.android.chefmonster.ApplicationLoader;
- import com.android.chefmonster.Cart.CartTabbedActivity;
- import com.android.chefmonster.Checkout.Coupons.Coupon;
- import com.android.chefmonster.Database.DBHelper_New;
- import com.android.chefmonster.Orders.Myorders;
- import com.android.chefmonster.Orders.OrdersTabbedActivity;
- import com.android.chefmonster.Payment.PaymentRequest;
- import com.android.chefmonster.Payment.PaymentResponse;
- import com.android.chefmonster.R;
- import com.android.chefmonster.UI.Login.Login;
- import com.android.chefmonster.UI.MainActivity;
- import com.android.chefmonster.Utills.Constants;
- import com.ivankocijan.magicviews.views.MagicButton;
- import com.ivankocijan.magicviews.views.MagicEditText;
- import com.ivankocijan.magicviews.views.MagicTextView;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.IOException;
- import java.nio.charset.Charset;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
- import java.util.concurrent.ThreadLocalRandom;
- import co.ceryle.radiorealbutton.RadioRealButton;
- import co.ceryle.radiorealbutton.RadioRealButtonGroup;
- import okhttp3.Call;
- import okhttp3.Callback;
- import okhttp3.FormBody;
- import okhttp3.MediaType;
- import okhttp3.OkHttpClient;
- import okhttp3.Request;
- import okhttp3.RequestBody;
- import okhttp3.Response;
- public class Checkout extends AppCompatActivity implements View.OnClickListener {
- protected MagicEditText coupon;
- protected MagicButton btnApplyCoupon;
- protected LinearLayout lytApplyCoupon;
- protected LinearLayout aftCouponApply;
- protected ImageView addFriend;
- protected MagicTextView userProfileName;
- protected MagicTextView userProfileShortBio;
- protected RelativeLayout profileLayout;
- protected MagicTextView couponAppliedLbl;
- protected TextView ivAddrNav;
- protected ImageView ivOrderNav;
- protected MagicTextView orderInfo;
- protected LinearLayout lytOrderConfirm;
- protected MagicTextView magicTextView6;
- protected LinearLayout lytPayment;
- protected MagicButton btnConfirmOrder;
- protected RecyclerView rvOrderInfo;
- protected ImageView ivApplyCoupen;
- TextView tv_total_price, tv_chkoutAddress, tv_orderInfo, deliveryInfo, tv_username, tv_userEmail, tv_click_confirmAddr,tv_apply_click;
- Button btn_confirm_order;
- ImageView userProfile;
- String OrderList = "";
- String addressInfo = "";
- private Toolbar mToolbar;
- private Context mContext;
- RadioRealButton rbCod;
- RadioRealButton rbPol;
- RadioRealButtonGroup rgPaymentMethod;
- JSONArray jarray;
- static DBHelper_New dbhelper;
- ArrayList<ArrayList<Object>> data;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- super.setContentView(R.layout.activity_checkout_new);
- setUpToolbar();
- bindUI();
- //login validation
- if (ApplicationLoader.getUserEmail().isEmpty()) {
- Intent in = new Intent(getApplicationContext(), Login.class);
- startActivityForResult(in, 2314);
- }
- dbhelper = new DBHelper_New(getApplicationContext());
- validatePhone();
- //pin validation
- //setting data to resources
- jarray = new JSONArray();
- try {
- getDataFromDatabase();
- } catch (JSONException e) {
- e.printStackTrace();
- }
- int randomNum = ThreadLocalRandom.current().nextInt(150000, 1000000 + 1);
- txnid =randomNum+"";
- }
- private void setUpToolbar() {
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarr);
- setSupportActionBar(toolbar);
- ImageView iv_menu_nav = (ImageView) findViewById(R.id.iv_menu_nav);
- TextView tv_title = (TextView) findViewById(R.id.txtTitle);
- tv_title.setText("Checkout");
- iv_menu_nav.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- startActivity(new Intent(Checkout.this, CartTabbedActivity.class));
- finish();
- }
- });
- }
- public void validatePhone() {
- if (ApplicationLoader.getUserPhone().isEmpty()) {
- System.out.println("OTP Screen");
- } else {
- }
- //goto pin validation screen
- }
- String result;
- ProgressDialog dialog;
- String flatno="",landmarks="";
- String txnid;
- public void confirmOrder() throws JSONException {
- if (tv_chkoutAddress.getText().toString().contains("Click here to add address")) {
- Toast.makeText(getApplicationContext(), "Please Enter Valid Address", Toast.LENGTH_SHORT).show();
- tv_chkoutAddress.requestFocus();
- tv_chkoutAddress.setTextColor(Color.RED);
- }
- else if (flatno.toString().length()<=1 && landmarks.toString().length()<=1 ) {
- Toast.makeText(getApplicationContext(), "Please Enter Valid Address", Toast.LENGTH_SHORT).show();
- tv_chkoutAddress.requestFocus();
- tv_chkoutAddress.setTextColor(Color.RED);
- }
- else {
- dialog = ProgressDialog.show(Checkout.this, "", "Placing your order, Please Wait", true);
- //System.out.println(jarray.toString()+"*************");
- //send to server
- final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
- OkHttpClient client = new OkHttpClient();
- // RequestBody body = RequestBody.create(JSON,jarray.toString());
- FormBody.Builder formBody;
- formBody = new FormBody.Builder()
- .add("jarry", jarray.toString())
- .add("custemail", ApplicationLoader.getUserEmail())
- .add("Address", tv_chkoutAddress.getText().toString())
- .add("OrderPrice", String.valueOf(Order_price))
- .add("orderlatitude", ApplicationLoader.getUserLat())
- .add("typeofpayment",type_of_payment)
- .add("orderlongitude", ApplicationLoader.getUserLon())
- .add("transid",txnid);
- RequestBody formBodyA = formBody.build();
- Request request = new Request.Builder()
- .url(Constants.SendDataAPI)
- .post(formBodyA)
- .build();
- client.newCall(request).enqueue(new Callback() {
- @Override
- public void onFailure(Call call, IOException e) {
- }
- @Override
- public void onResponse(Call call, Response response) throws IOException {
- if (response.isSuccessful()) {
- dialog.dismiss();
- result = response.body().string();
- // System.out.println(result);
- /* Intent intent=new Intent(Checkout.this, PaymentRequest.class);
- intent.putExtra("txnid",result);
- intent.putExtra("totalamount",ApplicationLoader.round(total_order_value, 2)+"");
- startActivity(intent);
- */
- System.out.println(result);
- dbhelper.deleteAllData();
- startActivity(new Intent(Checkout.this, OrdersTabbedActivity.class));
- finish();
- }
- }
- });
- }
- }
- private static final Charset UTF8 = Charset.forName("UTF-8");
- public void bindUI() {
- tv_total_price = (TextView) findViewById(R.id.tv_total_price);
- tv_chkoutAddress = (TextView) findViewById(R.id.chkoutAddress);
- tv_orderInfo = (TextView) findViewById(R.id.orderInfo);
- deliveryInfo = (TextView) findViewById(R.id.deliveryInfo);
- btn_confirm_order = (Button) findViewById(R.id.btn_confirm_order);
- tv_username = (TextView) findViewById(R.id.user_profile_name);
- tv_userEmail = (TextView) findViewById(R.id.user_profile_short_bio);
- userProfile = (ImageView) findViewById(R.id.user_profile_photo);
- tv_click_confirmAddr = (TextView) findViewById(R.id.tv_click_confirmAddr);
- tv_click_confirmAddr.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- addressUpdate();
- }
- });
- tv_chkoutAddress.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- addressUpdate();
- }
- });
- btn_confirm_order.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if(pickupCheck){
- Intent intent=new Intent(Checkout.this, PaymentRequest.class);
- intent.putExtra("txnid",txnid);
- intent.putExtra("totalamount",ApplicationLoader.round(total_order_value, 2)+"");
- startActivityForResult(intent,5647);
- }
- else
- {
- try {
- confirmOrder();
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- }
- });
- initView();
- /*
- Picasso.with(Checkout.this)
- .load(url)
- .resize(50, 50)
- .centerCrop()
- .transform(Transformation.class)
- .into()*/
- }
- public void setUserInfo() {
- if (!ApplicationLoader.getUserName().isEmpty()) {
- tv_username.setText(ApplicationLoader.getUserName());
- tv_userEmail.setText(ApplicationLoader.getUserEmail());
- }
- }
- double Order_price = 0;
- String OrderList2 = "";
- List<CheckoutOrder> mCheckoutOrders;
- Boolean pickupCheck=false;
- public void getDataFromDatabase() throws JSONException {
- data = dbhelper.getAllData();
- if (data.size() > 0) {
- double Total_price = 0;
- double tax = 0;
- // store all data to variables
- for (int i = 0; i < data.size(); i++) {
- CheckoutOrder mCheckoutOrder = new CheckoutOrder();
- ArrayList<Object> row = data.get(i);
- JSONObject orderObj = new JSONObject();
- String Menu_id = row.get(0).toString();
- String Menu_name = row.get(1).toString();
- String Quantity = row.get(2).toString();
- double Sub_total_price = Double.parseDouble(row.get(3).toString());
- String Menu_delivery_type = row.get(4).toString();
- Order_price += Sub_total_price;
- // calculate order price
- OrderList += (Menu_name + " " + Quantity + " " + Sub_total_price + " ₹,\n");
- mCheckoutOrder.setMenuName(Menu_name);
- mCheckoutOrder.setMenuQty(Quantity);
- mCheckoutOrder.setMenuPrice(Sub_total_price + " ₹");
- //
- orderObj.put("Menu_id", Menu_id);
- orderObj.put("Menu_name", Menu_name);
- orderObj.put("Menu_qty", Quantity);
- orderObj.put("price", String.valueOf(Sub_total_price));
- orderObj.put("delivery_type", Menu_delivery_type);
- if(!pickupCheck && Menu_delivery_type.equalsIgnoreCase("PICKUP"))
- {
- pickupCheck=true;
- rgPaymentMethod.setPosition(1);
- rgPaymentMethod.setEnabled(false);
- rgPaymentMethod.setClickable(false);
- Toast.makeText(Checkout.this, "When Pickup items are there .Payment should be done by online only.", Toast.LENGTH_LONG).show();
- type_of_payment="Online";
- }
- jarray.put(orderObj);
- mCheckoutOrders.add(mCheckoutOrder);
- }
- if (OrderList.equalsIgnoreCase("")) {
- OrderList += getString(R.string.no_order_menu);
- }
- //server hit to get taxes
- total_order_value = ApplicationLoader.round(Order_price + (Order_price * 14.5) / 100, 2);
- OrderList2 = OrderList + "Order Cost : " + Order_price + " ₹,\n";
- OrderList2 += "Order Tax : " + String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹,\n";
- OrderList2 += "Total Cost : " + ApplicationLoader.round(total_order_value, 2) + " ₹.\n";
- itemTotal.setText(Order_price + " ₹");
- taxTotal.setText(String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹");
- deliveryChargesTotal.setText("0.0");
- tvGrandTotal.setText(ApplicationLoader.round(total_order_value, 2) + " ₹");
- final double finalOrder_price = ApplicationLoader.round(total_order_value, 2);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- tv_total_price.setText(finalOrder_price + " ₹");
- tv_orderInfo.setText(OrderList2);
- }
- });
- } else {
- Intent intent = new Intent(Checkout.this, CartTabbedActivity.class);
- Toast.makeText(Checkout.this, "No Items Found in cart for checkout!.", Toast.LENGTH_SHORT).show();
- startActivity(intent);
- finish();
- }
- OrderInfoAdapter oia = new OrderInfoAdapter(mCheckoutOrders);
- rvOrderInfo.setAdapter(oia);
- }
- double total_order_value = 0.0;
- String type_of_payment="COD";
- protected void addressUpdate() {
- View adv = getLayoutInflater().inflate(R.layout.addressdialog, null, false);
- final EditText locadr = (EditText) adv.findViewById(R.id.fullAddr);
- final AutoCompleteTextView bnfn = (AutoCompleteTextView) adv.findViewById(R.id.adrbnfn);
- final AutoCompleteTextView landmark = (AutoCompleteTextView) adv.findViewById(R.id.adrlandmark);
- final EditText adrphone = (EditText) adv.findViewById(R.id.adrphone);
- ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
- android.R.layout.simple_dropdown_item_1line, dbhelper.getCheckoutLandmark());
- ArrayAdapter<String> adp1 = new ArrayAdapter<String>(this,
- android.R.layout.simple_dropdown_item_1line, dbhelper.getCheckoutBuilding());
- bnfn.setThreshold(1);
- bnfn.setAdapter(adp1);
- landmark.setThreshold(1);
- landmark.setAdapter(adp);
- locadr.setText(ApplicationLoader.getUserLocation());
- locadr.setFocusable(false);
- adrphone.setText(ApplicationLoader.getUserPhone());
- boolean wrapInScrollView = true;
- new MaterialDialog.Builder(this)
- .autoDismiss(false)
- .title("Confirm Address")
- .customView(adv, wrapInScrollView)
- .positiveText("Confirm")
- .onPositive(new MaterialDialog.SingleButtonCallback() {
- @Override
- public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
- if(bnfn.getText().toString().length() > 1 && landmark.getText().toString().length() > 1)
- {
- addressInfo = bnfn.getText().toString() + ",\n" + landmark.getText().toString() + ", \n" + ApplicationLoader.getUserLocation() + ", \n"
- + ApplicationLoader.getUserCity();
- tv_chkoutAddress.setText(addressInfo);
- flatno=bnfn.getText().toString();
- landmarks= landmark.getText().toString();
- ivAddrNav.setText(landmark.getText().toString()+","+ApplicationLoader.getUserCity());
- dbhelper.addCheckoutAddr(landmark.getText().toString(), bnfn.getText().toString());
- dialog.dismiss();
- }
- else
- {
- Toast.makeText(Checkout.this, "Flat No and Landmark are required, please add", Toast.LENGTH_LONG).show();
- }
- }
- })
- .negativeText("Cancel")
- .onNegative(new MaterialDialog.SingleButtonCallback() {
- @Override
- public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
- dialog.dismiss();
- }
- })
- .show();
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == 1234 && resultCode == RESULT_OK) {
- tv_username.setText(ApplicationLoader.getUserName());
- tv_userEmail.setText(ApplicationLoader.getUserEmail());
- } else if(requestCode==5647 && resultCode==RESULT_OK){
- //check payment status
- if(data.getExtras().getString("status").equalsIgnoreCase("success"))
- {
- //payment success
- // showProgressDialog("Confirming Order");
- try {
- confirmOrder();
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- else
- {
- Toast.makeText(Checkout.this, "Unable to place order,please try again", Toast.LENGTH_SHORT).show();
- }
- }
- }
- @Override
- protected void onResume() {
- super.onResume();
- tv_username.setText(ApplicationLoader.getUserName());
- tv_userEmail.setText(ApplicationLoader.getUserEmail());
- }
- @Override
- public void onClick(View view) {
- if (view.getId() == R.id.btnApplyCoupon) {
- if (coupon.getText().toString().length() > 1) {
- checkCoupon(coupon.getText().toString());
- } else
- Toast.makeText(Checkout.this, "Invalid Coupon", Toast.LENGTH_SHORT).show();
- } else if (view.getId() == R.id.couponAppliedLbl) {
- Toast.makeText(Checkout.this, "Long Press on this , to remove coupon", Toast.LENGTH_SHORT).show();
- } else if (view.getId() == R.id.iv_addr_nav) {
- addressUpdate();
- /* if (tv_chkoutAddress.getVisibility() == View.GONE) {
- tv_chkoutAddress.setVisibility(View.VISIBLE);
- ivAddrNav.setImageResource(R.drawable.ic_expand_more);
- } else {
- tv_chkoutAddress.setVisibility(View.GONE);
- ivAddrNav.setImageResource(R.drawable.ic_navigate_next);
- }
- */
- } else if (view.getId() == R.id.iv_order_nav) {
- /*if (tv_orderInfo.getVisibility() == View.GONE) {
- tv_orderInfo.setVisibility(View.VISIBLE);
- ivOrderNav.setImageResource(R.drawable.ic_expand_more);
- } else {
- tv_orderInfo.setVisibility(View.GONE);
- ivOrderNav.setImageResource(R.drawable.ic_navigate_next);
- }*/
- } else if (view.getId() == R.id.iv_apply_coupen) {
- mLytBeforeCoupon.setVisibility(View.GONE);
- mLytAfterCoupon.setVisibility(View.VISIBLE);
- }
- }
- private void initView() {
- coupon = (MagicEditText) findViewById(R.id.coupon);
- btnApplyCoupon = (MagicButton) findViewById(R.id.btnApplyCoupon);
- btnApplyCoupon.setOnClickListener(Checkout.this);
- lytApplyCoupon = (LinearLayout) findViewById(R.id.lytApplyCoupon);
- aftCouponApply = (LinearLayout) findViewById(R.id.aftCouponApply);
- deliveryInfo = (MagicTextView) findViewById(R.id.deliveryInfo);
- addFriend = (ImageView) findViewById(R.id.add_friend);
- userProfileName = (MagicTextView) findViewById(R.id.user_profile_name);
- userProfileShortBio = (MagicTextView) findViewById(R.id.user_profile_short_bio);
- profileLayout = (RelativeLayout) findViewById(R.id.profile_layout);
- couponAppliedLbl = (MagicTextView) findViewById(R.id.couponAppliedLbl);
- couponAppliedLbl.setOnClickListener(Checkout.this);
- rbCod = (RadioRealButton) findViewById(R.id.rb_cod);
- rbPol = (RadioRealButton) findViewById(R.id.rb_pol);
- rgPaymentMethod = (RadioRealButtonGroup) findViewById(R.id.rgPaymentMethod);
- rgPaymentMethod.setOnClickedButtonListener(new RadioRealButtonGroup.OnClickedButtonListener() {
- @Override
- public void onClickedButton(RadioRealButton button, int position) {
- if(position==0)
- {
- if(pickupCheck)
- {
- rgPaymentMethod.setPosition(1,true);
- Toast.makeText(Checkout.this, "Sorry, When Pickup items are there . Payment should be done by online only." + position, Toast.LENGTH_LONG).show();
- }
- type_of_payment="COD";
- }
- else
- {
- type_of_payment="Online";
- }
- }
- });
- couponAppliedLbl.setOnLongClickListener(new View.OnLongClickListener() {
- @Override
- public boolean onLongClick(View view) {
- Intent intent = getIntent();
- intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
- finish();
- startActivity(intent);
- return false;
- }
- });
- lblItemTotal = (MagicTextView) findViewById(R.id.lblItemTotal);
- itemTotal = (MagicTextView) findViewById(R.id.itemTotal);
- lblTax = (MagicTextView) findViewById(R.id.lblTax);
- taxTotal = (MagicTextView) findViewById(R.id.taxTotal);
- applyCouponlbl = (MagicTextView) findViewById(R.id.applyCouponlbl);
- lblDeliveryCharges = (MagicTextView) findViewById(R.id.lblDeliveryCharges);
- deliveryChargesTotal = (MagicTextView) findViewById(R.id.deliveryChargesTotal);
- lblGrandTotal = (MagicTextView) findViewById(R.id.lblGrandTotal);
- tvGrandTotal = (MagicTextView) findViewById(R.id.tvGrandTotal);
- ivAddrNav = (TextView) findViewById(R.id.iv_addr_nav);
- ivAddrNav.setOnClickListener(Checkout.this);
- ivOrderNav = (ImageView) findViewById(R.id.iv_order_nav);
- ivOrderNav.setOnClickListener(Checkout.this);
- orderInfo = (MagicTextView) findViewById(R.id.orderInfo);
- lytOrderConfirm = (LinearLayout) findViewById(R.id.lytOrderConfirm);
- lytPayment = (LinearLayout) findViewById(R.id.lytPayment);
- btnConfirmOrder = (MagicButton) findViewById(R.id.btn_confirm_order);
- mLytBeforeCoupon = (LinearLayout) findViewById(R.id.lytBeforeCoupon);
- mLytAfterCoupon = (LinearLayout) findViewById(R.id.lytAfterCoupon);
- mAftapplyCouponlbl = (MagicTextView) findViewById(R.id.aftapplyCouponlbl);
- mAppliedCouponName = (MagicTextView) findViewById(R.id.appliedCouponName);
- mBtnCancelCoupon = (ImageView) findViewById(R.id.btnCancelCoupon);
- mCoupondiscount = (MagicTextView) findViewById(R.id.coupondiscount);
- rvOrderInfo = (RecyclerView) findViewById(R.id.rv_order_info);
- RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(Checkout.this);
- rvOrderInfo.setLayoutManager(mLayoutManager);
- rvOrderInfo.setItemAnimator(new DefaultItemAnimator());
- mCheckoutOrders = new ArrayList<>();
- ivApplyCoupen = (ImageView) findViewById(R.id.iv_apply_coupen);
- ivApplyCoupen.setOnClickListener(Checkout.this);
- }
- public void checkCoupon(String couponName) {
- showProgressDialog("Verifying Coupon.....");
- // checkCoupon=true&couponName=UGADHIOFF&useremail=santoshvarma4u@gmail.com
- String mUrl = Constants.checkCouponUrl + "?checkCoupon=true&useremail=" + ApplicationLoader.getUserEmail() + "&couponName=" + couponName;
- Log.d("murl", mUrl);
- OkHttpClient client = new OkHttpClient();
- Request request = new Request.Builder()
- .url(mUrl)
- .build();
- client.newCall(request).enqueue(new Callback() {
- @Override
- public void onFailure(Call request, IOException e) {
- e.printStackTrace();
- }
- @Override
- public void onResponse(Call call,final Response response) throws IOException {
- if (!response.isSuccessful()) {
- throw new IOException("Unexpected code " + response);
- } else {
- closeDialog();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- try {
- parseJSONData(response.body().string());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- }
- }
- });
- }
- private MagicTextView lblItemTotal;
- private MagicTextView itemTotal;
- private MagicTextView lblTax;
- private MagicTextView taxTotal;
- private MagicTextView applyCouponlbl;
- private MagicTextView lblDeliveryCharges;
- private MagicTextView deliveryChargesTotal;
- private MagicTextView lblGrandTotal;
- private MagicTextView tvGrandTotal;
- private LinearLayout mLytBeforeCoupon;
- private LinearLayout mLytAfterCoupon;
- private MagicTextView mAftapplyCouponlbl;
- private MagicTextView mAppliedCouponName;
- private ImageView mBtnCancelCoupon;
- private MagicTextView mCoupondiscount;
- List<Coupon> coupensList;
- String coupenApplied = "";
- public void parseJSONData(String strResponse) {
- coupensList = new ArrayList<>();
- try {
- // parse json data and store into arraylist variables
- JSONObject json = new JSONObject(strResponse);
- JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
- if (data.length() > 0) {
- for (int ii = 0; ii < data.length(); ii++) {
- //int i = 0;
- JSONObject object = data.getJSONObject(ii);
- JSONObject coupons = object.getJSONObject("coupons");
- Log.e("coupons", coupons.toString());
- Coupon cp = new Coupon();
- if (coupons.getString("response").equalsIgnoreCase("success")) {
- cp.setId(coupons.getInt("id"));
- cp.setDate_time(coupons.getString("date_time"));
- cp.setCouponname(coupons.getString("couponname"));
- cp.setCoupontype(coupons.getString("coupontype"));
- cp.setCouponvalue(coupons.getString("couponvalue"));
- cp.setExpirydate(coupons.getString("expirydate"));
- cp.setRepeatcount(coupons.getString("repeatcount"));
- cp.setResponse(coupons.getString("response"));
- coupensList.add(cp);
- UpdateCouponOrder(coupensList);
- coupenApplied = "true";
- } else {
- coupenApplied = "false";
- Toast.makeText(Checkout.this, "Invalid Coupon", Toast.LENGTH_SHORT).show();
- }
- }
- InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.hideSoftInputFromWindow(getWindow().getDecorView().getRootView().getWindowToken(), 0);
- } else {
- coupenApplied = "false";
- Toast.makeText(Checkout.this, "Invalid Coupon", Toast.LENGTH_SHORT).show();
- }
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void UpdateCouponOrder(List<Coupon> coupon) {
- /* mLytBeforeCoupon.setVisibility(View.VISIBLE);
- mLytAfterCoupon.setVisibility(View.VISIBLE);*/
- mAppliedCouponName.setText(coupon.get(0).getCouponname().toString());
- if (coupon.get(0).getCoupontype().equalsIgnoreCase("P"))//for percentage
- {
- Double percentageValue = Double.parseDouble(coupon.get(0).getCouponvalue().toString());
- final Double discountPrice = total_order_value * percentageValue / 100;
- total_order_value = total_order_value - discountPrice;
- OrderList2 = "";
- // total_order_value = ApplicationLoader.round(Order_price + (Order_price * 14.5) / 100, 2);
- OrderList2 = OrderList + "Order Cost : " + Order_price + " ₹,\n";
- OrderList2 += "Order Tax : " + String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹,\n";
- OrderList2 += "Coupon Applied - " + discountPrice + ",\n";
- OrderList2 += "Total Cost : " + ApplicationLoader.round(total_order_value, 2) + " ₹.\n";
- final double finalOrder_price = ApplicationLoader.round(total_order_value, 2);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- tv_total_price.setText(finalOrder_price + " ₹");
- tv_orderInfo.setText(OrderList2);
- itemTotal.setText(Order_price + " ₹");
- taxTotal.setText(String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹");
- deliveryChargesTotal.setText("0.0");
- mCoupondiscount.setText(discountPrice + " ₹");
- tvGrandTotal.setText(String.valueOf(ApplicationLoader.round(total_order_value, 2)) + " ₹");
- }
- });
- } else if (coupon.get(0).getCoupontype().equalsIgnoreCase("R"))//for rates
- {
- final Double discountPrice = Double.parseDouble(coupon.get(0).getCouponvalue().toString());
- total_order_value = total_order_value - discountPrice;
- OrderList2 = "";
- // total_order_value = ApplicationLoader.round(Order_price + (Order_price * 14.5) / 100, 2);
- OrderList2 = OrderList + "Order Cost : " + Order_price + " ₹,\n";
- OrderList2 += "Order Tax : " + String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹,\n";
- OrderList2 += "Coupon Applied - " + discountPrice + ",\n";
- OrderList2 += "Total Cost : " + ApplicationLoader.round(total_order_value, 2) + " ₹.\n";
- final double finalOrder_price = ApplicationLoader.round(total_order_value, 2);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- tv_total_price.setText(finalOrder_price + " ₹");
- tv_orderInfo.setText(OrderList2);
- itemTotal.setText(Order_price + " ₹");
- taxTotal.setText(String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹");
- deliveryChargesTotal.setText("0.0");
- mCoupondiscount.setText(discountPrice + " ₹");
- tvGrandTotal.setText(String.valueOf(ApplicationLoader.round(total_order_value, 2)) + " ₹");
- }
- });
- }
- /* lytApplyCoupon.setVisibility(View.GONE);
- aftCouponApply.setVisibility(View.VISIBLE);*/
- }
- ProgressDialog pd;
- public void showProgressDialog(String msg) {
- if (pd == null)
- pd = new ProgressDialog(Checkout.this);
- pd.setMessage("loading...");
- pd.setCancelable(false);
- pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
- @Override
- public void onDismiss(DialogInterface dialogInterface) {
- dialogInterface.dismiss();
- }
- });
- pd.show();
- }
- public void closeDialog() {
- // do something wih the result
- if (pd != null)
- pd.dismiss();
- }
- public class OrderInfoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
- List<CheckoutOrder> checkoutOrders;
- public OrderInfoAdapter(List<CheckoutOrder> orders) {
- this.checkoutOrders = orders;
- }
- @Override
- public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
- LayoutInflater li = LayoutInflater.from(parent.getContext());
- View view = li.inflate(R.layout.item_checkout_order, parent, false);
- RecyclerView.ViewHolder vHoder = new ViewHolderRow(view);
- return vHoder;
- }
- @Override
- public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
- ViewHolderRow viewholderOrder = (ViewHolderRow) holder;
- viewholderOrder.tv_MenuName.setText(checkoutOrders.get(position).getMenuName());
- viewholderOrder.tv_MenuQty.setText(checkoutOrders.get(position).getMenuQty());
- viewholderOrder.tv_MenuPrice.setText(checkoutOrders.get(position).getMenuPrice());
- }
- @Override
- public int getItemCount() {
- return checkoutOrders.size();
- }
- }
- public class ViewHolderRow extends RecyclerView.ViewHolder {
- TextView tv_MenuName, tv_MenuQty, tv_MenuPrice;
- public ViewHolderRow(View itemView) {
- super(itemView);
- tv_MenuName = (TextView) itemView.findViewById(R.id.tv_MenuName);
- tv_MenuQty = (TextView) itemView.findViewById(R.id.tv_MenuQty);
- tv_MenuPrice = (TextView) itemView.findViewById(R.id.tv_MenuPrice);
- }
- }
- }