PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  1. package com.android.chefmonster.Checkout;
  2. import android.app.ProgressDialog;
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.content.Intent;
  6. import android.graphics.Color;
  7. import android.os.Bundle;
  8. import android.support.annotation.NonNull;
  9. import android.support.v7.app.AppCompatActivity;
  10. import android.support.v7.widget.DefaultItemAnimator;
  11. import android.support.v7.widget.LinearLayoutManager;
  12. import android.support.v7.widget.RecyclerView;
  13. import android.support.v7.widget.Toolbar;
  14. import android.util.Log;
  15. import android.view.LayoutInflater;
  16. import android.view.View;
  17. import android.view.ViewGroup;
  18. import android.view.inputmethod.InputMethodManager;
  19. import android.widget.ArrayAdapter;
  20. import android.widget.AutoCompleteTextView;
  21. import android.widget.Button;
  22. import android.widget.EditText;
  23. import android.widget.ImageView;
  24. import android.widget.LinearLayout;
  25. import android.widget.RelativeLayout;
  26. import android.widget.TextView;
  27. import android.widget.Toast;
  28. import com.afollestad.materialdialogs.DialogAction;
  29. import com.afollestad.materialdialogs.MaterialDialog;
  30. import com.android.chefmonster.ApplicationLoader;
  31. import com.android.chefmonster.Cart.CartTabbedActivity;
  32. import com.android.chefmonster.Checkout.Coupons.Coupon;
  33. import com.android.chefmonster.Database.DBHelper_New;
  34. import com.android.chefmonster.Orders.Myorders;
  35. import com.android.chefmonster.Orders.OrdersTabbedActivity;
  36. import com.android.chefmonster.Payment.PaymentRequest;
  37. import com.android.chefmonster.Payment.PaymentResponse;
  38. import com.android.chefmonster.R;
  39. import com.android.chefmonster.UI.Login.Login;
  40. import com.android.chefmonster.UI.MainActivity;
  41. import com.android.chefmonster.Utills.Constants;
  42. import com.ivankocijan.magicviews.views.MagicButton;
  43. import com.ivankocijan.magicviews.views.MagicEditText;
  44. import com.ivankocijan.magicviews.views.MagicTextView;
  45. import org.json.JSONArray;
  46. import org.json.JSONException;
  47. import org.json.JSONObject;
  48. import java.io.IOException;
  49. import java.nio.charset.Charset;
  50. import java.util.ArrayList;
  51. import java.util.List;
  52. import java.util.UUID;
  53. import java.util.concurrent.ThreadLocalRandom;
  54. import co.ceryle.radiorealbutton.RadioRealButton;
  55. import co.ceryle.radiorealbutton.RadioRealButtonGroup;
  56. import okhttp3.Call;
  57. import okhttp3.Callback;
  58. import okhttp3.FormBody;
  59. import okhttp3.MediaType;
  60. import okhttp3.OkHttpClient;
  61. import okhttp3.Request;
  62. import okhttp3.RequestBody;
  63. import okhttp3.Response;
  64. public class Checkout extends AppCompatActivity implements View.OnClickListener {
  65. protected MagicEditText coupon;
  66. protected MagicButton btnApplyCoupon;
  67. protected LinearLayout lytApplyCoupon;
  68. protected LinearLayout aftCouponApply;
  69. protected ImageView addFriend;
  70. protected MagicTextView userProfileName;
  71. protected MagicTextView userProfileShortBio;
  72. protected RelativeLayout profileLayout;
  73. protected MagicTextView couponAppliedLbl;
  74. protected TextView ivAddrNav;
  75. protected ImageView ivOrderNav;
  76. protected MagicTextView orderInfo;
  77. protected LinearLayout lytOrderConfirm;
  78. protected MagicTextView magicTextView6;
  79. protected LinearLayout lytPayment;
  80. protected MagicButton btnConfirmOrder;
  81. protected RecyclerView rvOrderInfo;
  82. protected ImageView ivApplyCoupen;
  83. TextView tv_total_price, tv_chkoutAddress, tv_orderInfo, deliveryInfo, tv_username, tv_userEmail, tv_click_confirmAddr,tv_apply_click;
  84. Button btn_confirm_order;
  85. ImageView userProfile;
  86. String OrderList = "";
  87. String addressInfo = "";
  88. private Toolbar mToolbar;
  89. private Context mContext;
  90. RadioRealButton rbCod;
  91. RadioRealButton rbPol;
  92. RadioRealButtonGroup rgPaymentMethod;
  93. JSONArray jarray;
  94. static DBHelper_New dbhelper;
  95. ArrayList<ArrayList<Object>> data;
  96. @Override
  97. protected void onCreate(Bundle savedInstanceState) {
  98. super.onCreate(savedInstanceState);
  99. super.setContentView(R.layout.activity_checkout_new);
  100. setUpToolbar();
  101. bindUI();
  102. //login validation
  103. if (ApplicationLoader.getUserEmail().isEmpty()) {
  104. Intent in = new Intent(getApplicationContext(), Login.class);
  105. startActivityForResult(in, 2314);
  106. }
  107. dbhelper = new DBHelper_New(getApplicationContext());
  108. validatePhone();
  109. //pin validation
  110. //setting data to resources
  111. jarray = new JSONArray();
  112. try {
  113. getDataFromDatabase();
  114. } catch (JSONException e) {
  115. e.printStackTrace();
  116. }
  117. int randomNum = ThreadLocalRandom.current().nextInt(150000, 1000000 + 1);
  118. txnid =randomNum+"";
  119. }
  120. private void setUpToolbar() {
  121. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarr);
  122. setSupportActionBar(toolbar);
  123. ImageView iv_menu_nav = (ImageView) findViewById(R.id.iv_menu_nav);
  124. TextView tv_title = (TextView) findViewById(R.id.txtTitle);
  125. tv_title.setText("Checkout");
  126. iv_menu_nav.setOnClickListener(new View.OnClickListener() {
  127. @Override
  128. public void onClick(View v) {
  129. startActivity(new Intent(Checkout.this, CartTabbedActivity.class));
  130. finish();
  131. }
  132. });
  133. }
  134. public void validatePhone() {
  135. if (ApplicationLoader.getUserPhone().isEmpty()) {
  136. System.out.println("OTP Screen");
  137. } else {
  138. }
  139. //goto pin validation screen
  140. }
  141. String result;
  142. ProgressDialog dialog;
  143. String flatno="",landmarks="";
  144. String txnid;
  145. public void confirmOrder() throws JSONException {
  146. if (tv_chkoutAddress.getText().toString().contains("Click here to add address")) {
  147. Toast.makeText(getApplicationContext(), "Please Enter Valid Address", Toast.LENGTH_SHORT).show();
  148. tv_chkoutAddress.requestFocus();
  149. tv_chkoutAddress.setTextColor(Color.RED);
  150. }
  151. else if (flatno.toString().length()<=1 && landmarks.toString().length()<=1 ) {
  152. Toast.makeText(getApplicationContext(), "Please Enter Valid Address", Toast.LENGTH_SHORT).show();
  153. tv_chkoutAddress.requestFocus();
  154. tv_chkoutAddress.setTextColor(Color.RED);
  155. }
  156. else {
  157. dialog = ProgressDialog.show(Checkout.this, "", "Placing your order, Please Wait", true);
  158. //System.out.println(jarray.toString()+"*************");
  159. //send to server
  160. final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  161. OkHttpClient client = new OkHttpClient();
  162. // RequestBody body = RequestBody.create(JSON,jarray.toString());
  163. FormBody.Builder formBody;
  164. formBody = new FormBody.Builder()
  165. .add("jarry", jarray.toString())
  166. .add("custemail", ApplicationLoader.getUserEmail())
  167. .add("Address", tv_chkoutAddress.getText().toString())
  168. .add("OrderPrice", String.valueOf(Order_price))
  169. .add("orderlatitude", ApplicationLoader.getUserLat())
  170. .add("typeofpayment",type_of_payment)
  171. .add("orderlongitude", ApplicationLoader.getUserLon())
  172. .add("transid",txnid);
  173. RequestBody formBodyA = formBody.build();
  174. Request request = new Request.Builder()
  175. .url(Constants.SendDataAPI)
  176. .post(formBodyA)
  177. .build();
  178. client.newCall(request).enqueue(new Callback() {
  179. @Override
  180. public void onFailure(Call call, IOException e) {
  181. }
  182. @Override
  183. public void onResponse(Call call, Response response) throws IOException {
  184. if (response.isSuccessful()) {
  185. dialog.dismiss();
  186. result = response.body().string();
  187. // System.out.println(result);
  188. /* Intent intent=new Intent(Checkout.this, PaymentRequest.class);
  189. intent.putExtra("txnid",result);
  190. intent.putExtra("totalamount",ApplicationLoader.round(total_order_value, 2)+"");
  191. startActivity(intent);
  192. */
  193. System.out.println(result);
  194. dbhelper.deleteAllData();
  195. startActivity(new Intent(Checkout.this, OrdersTabbedActivity.class));
  196. finish();
  197. }
  198. }
  199. });
  200. }
  201. }
  202. private static final Charset UTF8 = Charset.forName("UTF-8");
  203. public void bindUI() {
  204. tv_total_price = (TextView) findViewById(R.id.tv_total_price);
  205. tv_chkoutAddress = (TextView) findViewById(R.id.chkoutAddress);
  206. tv_orderInfo = (TextView) findViewById(R.id.orderInfo);
  207. deliveryInfo = (TextView) findViewById(R.id.deliveryInfo);
  208. btn_confirm_order = (Button) findViewById(R.id.btn_confirm_order);
  209. tv_username = (TextView) findViewById(R.id.user_profile_name);
  210. tv_userEmail = (TextView) findViewById(R.id.user_profile_short_bio);
  211. userProfile = (ImageView) findViewById(R.id.user_profile_photo);
  212. tv_click_confirmAddr = (TextView) findViewById(R.id.tv_click_confirmAddr);
  213. tv_click_confirmAddr.setOnClickListener(new View.OnClickListener() {
  214. @Override
  215. public void onClick(View view) {
  216. addressUpdate();
  217. }
  218. });
  219. tv_chkoutAddress.setOnClickListener(new View.OnClickListener() {
  220. @Override
  221. public void onClick(View view) {
  222. addressUpdate();
  223. }
  224. });
  225. btn_confirm_order.setOnClickListener(new View.OnClickListener() {
  226. @Override
  227. public void onClick(View v) {
  228. if(pickupCheck){
  229. Intent intent=new Intent(Checkout.this, PaymentRequest.class);
  230. intent.putExtra("txnid",txnid);
  231. intent.putExtra("totalamount",ApplicationLoader.round(total_order_value, 2)+"");
  232. startActivityForResult(intent,5647);
  233. }
  234. else
  235. {
  236. try {
  237. confirmOrder();
  238. } catch (JSONException e) {
  239. e.printStackTrace();
  240. }
  241. }
  242. }
  243. });
  244. initView();
  245. /*
  246. Picasso.with(Checkout.this)
  247. .load(url)
  248. .resize(50, 50)
  249. .centerCrop()
  250. .transform(Transformation.class)
  251. .into()*/
  252. }
  253. public void setUserInfo() {
  254. if (!ApplicationLoader.getUserName().isEmpty()) {
  255. tv_username.setText(ApplicationLoader.getUserName());
  256. tv_userEmail.setText(ApplicationLoader.getUserEmail());
  257. }
  258. }
  259. double Order_price = 0;
  260. String OrderList2 = "";
  261. List<CheckoutOrder> mCheckoutOrders;
  262. Boolean pickupCheck=false;
  263. public void getDataFromDatabase() throws JSONException {
  264. data = dbhelper.getAllData();
  265. if (data.size() > 0) {
  266. double Total_price = 0;
  267. double tax = 0;
  268. // store all data to variables
  269. for (int i = 0; i < data.size(); i++) {
  270. CheckoutOrder mCheckoutOrder = new CheckoutOrder();
  271. ArrayList<Object> row = data.get(i);
  272. JSONObject orderObj = new JSONObject();
  273. String Menu_id = row.get(0).toString();
  274. String Menu_name = row.get(1).toString();
  275. String Quantity = row.get(2).toString();
  276. double Sub_total_price = Double.parseDouble(row.get(3).toString());
  277. String Menu_delivery_type = row.get(4).toString();
  278. Order_price += Sub_total_price;
  279. // calculate order price
  280. OrderList += (Menu_name + " " + Quantity + " " + Sub_total_price + " ₹,\n");
  281. mCheckoutOrder.setMenuName(Menu_name);
  282. mCheckoutOrder.setMenuQty(Quantity);
  283. mCheckoutOrder.setMenuPrice(Sub_total_price + " ₹");
  284. //
  285. orderObj.put("Menu_id", Menu_id);
  286. orderObj.put("Menu_name", Menu_name);
  287. orderObj.put("Menu_qty", Quantity);
  288. orderObj.put("price", String.valueOf(Sub_total_price));
  289. orderObj.put("delivery_type", Menu_delivery_type);
  290. if(!pickupCheck && Menu_delivery_type.equalsIgnoreCase("PICKUP"))
  291. {
  292. pickupCheck=true;
  293. rgPaymentMethod.setPosition(1);
  294. rgPaymentMethod.setEnabled(false);
  295. rgPaymentMethod.setClickable(false);
  296. Toast.makeText(Checkout.this, "When Pickup items are there .Payment should be done by online only.", Toast.LENGTH_LONG).show();
  297. type_of_payment="Online";
  298. }
  299. jarray.put(orderObj);
  300. mCheckoutOrders.add(mCheckoutOrder);
  301. }
  302. if (OrderList.equalsIgnoreCase("")) {
  303. OrderList += getString(R.string.no_order_menu);
  304. }
  305. //server hit to get taxes
  306. total_order_value = ApplicationLoader.round(Order_price + (Order_price * 14.5) / 100, 2);
  307. OrderList2 = OrderList + "Order Cost : " + Order_price + " ₹,\n";
  308. OrderList2 += "Order Tax : " + String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹,\n";
  309. OrderList2 += "Total Cost : " + ApplicationLoader.round(total_order_value, 2) + " ₹.\n";
  310. itemTotal.setText(Order_price + " ₹");
  311. taxTotal.setText(String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹");
  312. deliveryChargesTotal.setText("0.0");
  313. tvGrandTotal.setText(ApplicationLoader.round(total_order_value, 2) + " ₹");
  314. final double finalOrder_price = ApplicationLoader.round(total_order_value, 2);
  315. runOnUiThread(new Runnable() {
  316. @Override
  317. public void run() {
  318. tv_total_price.setText(finalOrder_price + " ₹");
  319. tv_orderInfo.setText(OrderList2);
  320. }
  321. });
  322. } else {
  323. Intent intent = new Intent(Checkout.this, CartTabbedActivity.class);
  324. Toast.makeText(Checkout.this, "No Items Found in cart for checkout!.", Toast.LENGTH_SHORT).show();
  325. startActivity(intent);
  326. finish();
  327. }
  328. OrderInfoAdapter oia = new OrderInfoAdapter(mCheckoutOrders);
  329. rvOrderInfo.setAdapter(oia);
  330. }
  331. double total_order_value = 0.0;
  332. String type_of_payment="COD";
  333. protected void addressUpdate() {
  334. View adv = getLayoutInflater().inflate(R.layout.addressdialog, null, false);
  335. final EditText locadr = (EditText) adv.findViewById(R.id.fullAddr);
  336. final AutoCompleteTextView bnfn = (AutoCompleteTextView) adv.findViewById(R.id.adrbnfn);
  337. final AutoCompleteTextView landmark = (AutoCompleteTextView) adv.findViewById(R.id.adrlandmark);
  338. final EditText adrphone = (EditText) adv.findViewById(R.id.adrphone);
  339. ArrayAdapter<String> adp = new ArrayAdapter<String>(this,
  340. android.R.layout.simple_dropdown_item_1line, dbhelper.getCheckoutLandmark());
  341. ArrayAdapter<String> adp1 = new ArrayAdapter<String>(this,
  342. android.R.layout.simple_dropdown_item_1line, dbhelper.getCheckoutBuilding());
  343. bnfn.setThreshold(1);
  344. bnfn.setAdapter(adp1);
  345. landmark.setThreshold(1);
  346. landmark.setAdapter(adp);
  347. locadr.setText(ApplicationLoader.getUserLocation());
  348. locadr.setFocusable(false);
  349. adrphone.setText(ApplicationLoader.getUserPhone());
  350. boolean wrapInScrollView = true;
  351. new MaterialDialog.Builder(this)
  352. .autoDismiss(false)
  353. .title("Confirm Address")
  354. .customView(adv, wrapInScrollView)
  355. .positiveText("Confirm")
  356. .onPositive(new MaterialDialog.SingleButtonCallback() {
  357. @Override
  358. public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
  359. if(bnfn.getText().toString().length() > 1 && landmark.getText().toString().length() > 1)
  360. {
  361. addressInfo = bnfn.getText().toString() + ",\n" + landmark.getText().toString() + ", \n" + ApplicationLoader.getUserLocation() + ", \n"
  362. + ApplicationLoader.getUserCity();
  363. tv_chkoutAddress.setText(addressInfo);
  364. flatno=bnfn.getText().toString();
  365. landmarks= landmark.getText().toString();
  366. ivAddrNav.setText(landmark.getText().toString()+","+ApplicationLoader.getUserCity());
  367. dbhelper.addCheckoutAddr(landmark.getText().toString(), bnfn.getText().toString());
  368. dialog.dismiss();
  369. }
  370. else
  371. {
  372. Toast.makeText(Checkout.this, "Flat No and Landmark are required, please add", Toast.LENGTH_LONG).show();
  373. }
  374. }
  375. })
  376. .negativeText("Cancel")
  377. .onNegative(new MaterialDialog.SingleButtonCallback() {
  378. @Override
  379. public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
  380. dialog.dismiss();
  381. }
  382. })
  383. .show();
  384. }
  385. @Override
  386. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  387. super.onActivityResult(requestCode, resultCode, data);
  388. if (requestCode == 1234 && resultCode == RESULT_OK) {
  389. tv_username.setText(ApplicationLoader.getUserName());
  390. tv_userEmail.setText(ApplicationLoader.getUserEmail());
  391. } else if(requestCode==5647 && resultCode==RESULT_OK){
  392. //check payment status
  393. if(data.getExtras().getString("status").equalsIgnoreCase("success"))
  394. {
  395. //payment success
  396. // showProgressDialog("Confirming Order");
  397. try {
  398. confirmOrder();
  399. } catch (JSONException e) {
  400. e.printStackTrace();
  401. }
  402. }
  403. else
  404. {
  405. Toast.makeText(Checkout.this, "Unable to place order,please try again", Toast.LENGTH_SHORT).show();
  406. }
  407. }
  408. }
  409. @Override
  410. protected void onResume() {
  411. super.onResume();
  412. tv_username.setText(ApplicationLoader.getUserName());
  413. tv_userEmail.setText(ApplicationLoader.getUserEmail());
  414. }
  415. @Override
  416. public void onClick(View view) {
  417. if (view.getId() == R.id.btnApplyCoupon) {
  418. if (coupon.getText().toString().length() > 1) {
  419. checkCoupon(coupon.getText().toString());
  420. } else
  421. Toast.makeText(Checkout.this, "Invalid Coupon", Toast.LENGTH_SHORT).show();
  422. } else if (view.getId() == R.id.couponAppliedLbl) {
  423. Toast.makeText(Checkout.this, "Long Press on this , to remove coupon", Toast.LENGTH_SHORT).show();
  424. } else if (view.getId() == R.id.iv_addr_nav) {
  425. addressUpdate();
  426. /* if (tv_chkoutAddress.getVisibility() == View.GONE) {
  427. tv_chkoutAddress.setVisibility(View.VISIBLE);
  428. ivAddrNav.setImageResource(R.drawable.ic_expand_more);
  429. } else {
  430. tv_chkoutAddress.setVisibility(View.GONE);
  431. ivAddrNav.setImageResource(R.drawable.ic_navigate_next);
  432. }
  433. */
  434. } else if (view.getId() == R.id.iv_order_nav) {
  435. /*if (tv_orderInfo.getVisibility() == View.GONE) {
  436. tv_orderInfo.setVisibility(View.VISIBLE);
  437. ivOrderNav.setImageResource(R.drawable.ic_expand_more);
  438. } else {
  439. tv_orderInfo.setVisibility(View.GONE);
  440. ivOrderNav.setImageResource(R.drawable.ic_navigate_next);
  441. }*/
  442. } else if (view.getId() == R.id.iv_apply_coupen) {
  443. mLytBeforeCoupon.setVisibility(View.GONE);
  444. mLytAfterCoupon.setVisibility(View.VISIBLE);
  445. }
  446. }
  447. private void initView() {
  448. coupon = (MagicEditText) findViewById(R.id.coupon);
  449. btnApplyCoupon = (MagicButton) findViewById(R.id.btnApplyCoupon);
  450. btnApplyCoupon.setOnClickListener(Checkout.this);
  451. lytApplyCoupon = (LinearLayout) findViewById(R.id.lytApplyCoupon);
  452. aftCouponApply = (LinearLayout) findViewById(R.id.aftCouponApply);
  453. deliveryInfo = (MagicTextView) findViewById(R.id.deliveryInfo);
  454. addFriend = (ImageView) findViewById(R.id.add_friend);
  455. userProfileName = (MagicTextView) findViewById(R.id.user_profile_name);
  456. userProfileShortBio = (MagicTextView) findViewById(R.id.user_profile_short_bio);
  457. profileLayout = (RelativeLayout) findViewById(R.id.profile_layout);
  458. couponAppliedLbl = (MagicTextView) findViewById(R.id.couponAppliedLbl);
  459. couponAppliedLbl.setOnClickListener(Checkout.this);
  460. rbCod = (RadioRealButton) findViewById(R.id.rb_cod);
  461. rbPol = (RadioRealButton) findViewById(R.id.rb_pol);
  462. rgPaymentMethod = (RadioRealButtonGroup) findViewById(R.id.rgPaymentMethod);
  463. rgPaymentMethod.setOnClickedButtonListener(new RadioRealButtonGroup.OnClickedButtonListener() {
  464. @Override
  465. public void onClickedButton(RadioRealButton button, int position) {
  466. if(position==0)
  467. {
  468. if(pickupCheck)
  469. {
  470. rgPaymentMethod.setPosition(1,true);
  471. Toast.makeText(Checkout.this, "Sorry, When Pickup items are there . Payment should be done by online only." + position, Toast.LENGTH_LONG).show();
  472. }
  473. type_of_payment="COD";
  474. }
  475. else
  476. {
  477. type_of_payment="Online";
  478. }
  479. }
  480. });
  481. couponAppliedLbl.setOnLongClickListener(new View.OnLongClickListener() {
  482. @Override
  483. public boolean onLongClick(View view) {
  484. Intent intent = getIntent();
  485. intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
  486. finish();
  487. startActivity(intent);
  488. return false;
  489. }
  490. });
  491. lblItemTotal = (MagicTextView) findViewById(R.id.lblItemTotal);
  492. itemTotal = (MagicTextView) findViewById(R.id.itemTotal);
  493. lblTax = (MagicTextView) findViewById(R.id.lblTax);
  494. taxTotal = (MagicTextView) findViewById(R.id.taxTotal);
  495. applyCouponlbl = (MagicTextView) findViewById(R.id.applyCouponlbl);
  496. lblDeliveryCharges = (MagicTextView) findViewById(R.id.lblDeliveryCharges);
  497. deliveryChargesTotal = (MagicTextView) findViewById(R.id.deliveryChargesTotal);
  498. lblGrandTotal = (MagicTextView) findViewById(R.id.lblGrandTotal);
  499. tvGrandTotal = (MagicTextView) findViewById(R.id.tvGrandTotal);
  500. ivAddrNav = (TextView) findViewById(R.id.iv_addr_nav);
  501. ivAddrNav.setOnClickListener(Checkout.this);
  502. ivOrderNav = (ImageView) findViewById(R.id.iv_order_nav);
  503. ivOrderNav.setOnClickListener(Checkout.this);
  504. orderInfo = (MagicTextView) findViewById(R.id.orderInfo);
  505. lytOrderConfirm = (LinearLayout) findViewById(R.id.lytOrderConfirm);
  506. lytPayment = (LinearLayout) findViewById(R.id.lytPayment);
  507. btnConfirmOrder = (MagicButton) findViewById(R.id.btn_confirm_order);
  508. mLytBeforeCoupon = (LinearLayout) findViewById(R.id.lytBeforeCoupon);
  509. mLytAfterCoupon = (LinearLayout) findViewById(R.id.lytAfterCoupon);
  510. mAftapplyCouponlbl = (MagicTextView) findViewById(R.id.aftapplyCouponlbl);
  511. mAppliedCouponName = (MagicTextView) findViewById(R.id.appliedCouponName);
  512. mBtnCancelCoupon = (ImageView) findViewById(R.id.btnCancelCoupon);
  513. mCoupondiscount = (MagicTextView) findViewById(R.id.coupondiscount);
  514. rvOrderInfo = (RecyclerView) findViewById(R.id.rv_order_info);
  515. RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(Checkout.this);
  516. rvOrderInfo.setLayoutManager(mLayoutManager);
  517. rvOrderInfo.setItemAnimator(new DefaultItemAnimator());
  518. mCheckoutOrders = new ArrayList<>();
  519. ivApplyCoupen = (ImageView) findViewById(R.id.iv_apply_coupen);
  520. ivApplyCoupen.setOnClickListener(Checkout.this);
  521. }
  522. public void checkCoupon(String couponName) {
  523. showProgressDialog("Verifying Coupon.....");
  524. // checkCoupon=true&couponName=UGADHIOFF&useremail=santoshvarma4u@gmail.com
  525. String mUrl = Constants.checkCouponUrl + "?checkCoupon=true&useremail=" + ApplicationLoader.getUserEmail() + "&couponName=" + couponName;
  526. Log.d("murl", mUrl);
  527. OkHttpClient client = new OkHttpClient();
  528. Request request = new Request.Builder()
  529. .url(mUrl)
  530. .build();
  531. client.newCall(request).enqueue(new Callback() {
  532. @Override
  533. public void onFailure(Call request, IOException e) {
  534. e.printStackTrace();
  535. }
  536. @Override
  537. public void onResponse(Call call,final Response response) throws IOException {
  538. if (!response.isSuccessful()) {
  539. throw new IOException("Unexpected code " + response);
  540. } else {
  541. closeDialog();
  542. runOnUiThread(new Runnable() {
  543. @Override
  544. public void run() {
  545. try {
  546. parseJSONData(response.body().string());
  547. } catch (IOException e) {
  548. e.printStackTrace();
  549. }
  550. }
  551. });
  552. }
  553. }
  554. });
  555. }
  556. private MagicTextView lblItemTotal;
  557. private MagicTextView itemTotal;
  558. private MagicTextView lblTax;
  559. private MagicTextView taxTotal;
  560. private MagicTextView applyCouponlbl;
  561. private MagicTextView lblDeliveryCharges;
  562. private MagicTextView deliveryChargesTotal;
  563. private MagicTextView lblGrandTotal;
  564. private MagicTextView tvGrandTotal;
  565. private LinearLayout mLytBeforeCoupon;
  566. private LinearLayout mLytAfterCoupon;
  567. private MagicTextView mAftapplyCouponlbl;
  568. private MagicTextView mAppliedCouponName;
  569. private ImageView mBtnCancelCoupon;
  570. private MagicTextView mCoupondiscount;
  571. List<Coupon> coupensList;
  572. String coupenApplied = "";
  573. public void parseJSONData(String strResponse) {
  574. coupensList = new ArrayList<>();
  575. try {
  576. // parse json data and store into arraylist variables
  577. JSONObject json = new JSONObject(strResponse);
  578. JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
  579. if (data.length() > 0) {
  580. for (int ii = 0; ii < data.length(); ii++) {
  581. //int i = 0;
  582. JSONObject object = data.getJSONObject(ii);
  583. JSONObject coupons = object.getJSONObject("coupons");
  584. Log.e("coupons", coupons.toString());
  585. Coupon cp = new Coupon();
  586. if (coupons.getString("response").equalsIgnoreCase("success")) {
  587. cp.setId(coupons.getInt("id"));
  588. cp.setDate_time(coupons.getString("date_time"));
  589. cp.setCouponname(coupons.getString("couponname"));
  590. cp.setCoupontype(coupons.getString("coupontype"));
  591. cp.setCouponvalue(coupons.getString("couponvalue"));
  592. cp.setExpirydate(coupons.getString("expirydate"));
  593. cp.setRepeatcount(coupons.getString("repeatcount"));
  594. cp.setResponse(coupons.getString("response"));
  595. coupensList.add(cp);
  596. UpdateCouponOrder(coupensList);
  597. coupenApplied = "true";
  598. } else {
  599. coupenApplied = "false";
  600. Toast.makeText(Checkout.this, "Invalid Coupon", Toast.LENGTH_SHORT).show();
  601. }
  602. }
  603. InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
  604. imm.hideSoftInputFromWindow(getWindow().getDecorView().getRootView().getWindowToken(), 0);
  605. } else {
  606. coupenApplied = "false";
  607. Toast.makeText(Checkout.this, "Invalid Coupon", Toast.LENGTH_SHORT).show();
  608. }
  609. } catch (JSONException e) {
  610. // TODO Auto-generated catch block
  611. e.printStackTrace();
  612. }
  613. }
  614. public void UpdateCouponOrder(List<Coupon> coupon) {
  615. /* mLytBeforeCoupon.setVisibility(View.VISIBLE);
  616. mLytAfterCoupon.setVisibility(View.VISIBLE);*/
  617. mAppliedCouponName.setText(coupon.get(0).getCouponname().toString());
  618. if (coupon.get(0).getCoupontype().equalsIgnoreCase("P"))//for percentage
  619. {
  620. Double percentageValue = Double.parseDouble(coupon.get(0).getCouponvalue().toString());
  621. final Double discountPrice = total_order_value * percentageValue / 100;
  622. total_order_value = total_order_value - discountPrice;
  623. OrderList2 = "";
  624. // total_order_value = ApplicationLoader.round(Order_price + (Order_price * 14.5) / 100, 2);
  625. OrderList2 = OrderList + "Order Cost : " + Order_price + " ₹,\n";
  626. OrderList2 += "Order Tax : " + String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹,\n";
  627. OrderList2 += "Coupon Applied - " + discountPrice + ",\n";
  628. OrderList2 += "Total Cost : " + ApplicationLoader.round(total_order_value, 2) + " ₹.\n";
  629. final double finalOrder_price = ApplicationLoader.round(total_order_value, 2);
  630. runOnUiThread(new Runnable() {
  631. @Override
  632. public void run() {
  633. tv_total_price.setText(finalOrder_price + " ₹");
  634. tv_orderInfo.setText(OrderList2);
  635. itemTotal.setText(Order_price + " ₹");
  636. taxTotal.setText(String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹");
  637. deliveryChargesTotal.setText("0.0");
  638. mCoupondiscount.setText(discountPrice + " ₹");
  639. tvGrandTotal.setText(String.valueOf(ApplicationLoader.round(total_order_value, 2)) + " ₹");
  640. }
  641. });
  642. } else if (coupon.get(0).getCoupontype().equalsIgnoreCase("R"))//for rates
  643. {
  644. final Double discountPrice = Double.parseDouble(coupon.get(0).getCouponvalue().toString());
  645. total_order_value = total_order_value - discountPrice;
  646. OrderList2 = "";
  647. // total_order_value = ApplicationLoader.round(Order_price + (Order_price * 14.5) / 100, 2);
  648. OrderList2 = OrderList + "Order Cost : " + Order_price + " ₹,\n";
  649. OrderList2 += "Order Tax : " + String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹,\n";
  650. OrderList2 += "Coupon Applied - " + discountPrice + ",\n";
  651. OrderList2 += "Total Cost : " + ApplicationLoader.round(total_order_value, 2) + " ₹.\n";
  652. final double finalOrder_price = ApplicationLoader.round(total_order_value, 2);
  653. runOnUiThread(new Runnable() {
  654. @Override
  655. public void run() {
  656. tv_total_price.setText(finalOrder_price + " ₹");
  657. tv_orderInfo.setText(OrderList2);
  658. itemTotal.setText(Order_price + " ₹");
  659. taxTotal.setText(String.valueOf(ApplicationLoader.round((Order_price * 14.5) / 100, 2)) + " ₹");
  660. deliveryChargesTotal.setText("0.0");
  661. mCoupondiscount.setText(discountPrice + " ₹");
  662. tvGrandTotal.setText(String.valueOf(ApplicationLoader.round(total_order_value, 2)) + " ₹");
  663. }
  664. });
  665. }
  666. /* lytApplyCoupon.setVisibility(View.GONE);
  667. aftCouponApply.setVisibility(View.VISIBLE);*/
  668. }
  669. ProgressDialog pd;
  670. public void showProgressDialog(String msg) {
  671. if (pd == null)
  672. pd = new ProgressDialog(Checkout.this);
  673. pd.setMessage("loading...");
  674. pd.setCancelable(false);
  675. pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
  676. @Override
  677. public void onDismiss(DialogInterface dialogInterface) {
  678. dialogInterface.dismiss();
  679. }
  680. });
  681. pd.show();
  682. }
  683. public void closeDialog() {
  684. // do something wih the result
  685. if (pd != null)
  686. pd.dismiss();
  687. }
  688. public class OrderInfoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
  689. List<CheckoutOrder> checkoutOrders;
  690. public OrderInfoAdapter(List<CheckoutOrder> orders) {
  691. this.checkoutOrders = orders;
  692. }
  693. @Override
  694. public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  695. LayoutInflater li = LayoutInflater.from(parent.getContext());
  696. View view = li.inflate(R.layout.item_checkout_order, parent, false);
  697. RecyclerView.ViewHolder vHoder = new ViewHolderRow(view);
  698. return vHoder;
  699. }
  700. @Override
  701. public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
  702. ViewHolderRow viewholderOrder = (ViewHolderRow) holder;
  703. viewholderOrder.tv_MenuName.setText(checkoutOrders.get(position).getMenuName());
  704. viewholderOrder.tv_MenuQty.setText(checkoutOrders.get(position).getMenuQty());
  705. viewholderOrder.tv_MenuPrice.setText(checkoutOrders.get(position).getMenuPrice());
  706. }
  707. @Override
  708. public int getItemCount() {
  709. return checkoutOrders.size();
  710. }
  711. }
  712. public class ViewHolderRow extends RecyclerView.ViewHolder {
  713. TextView tv_MenuName, tv_MenuQty, tv_MenuPrice;
  714. public ViewHolderRow(View itemView) {
  715. super(itemView);
  716. tv_MenuName = (TextView) itemView.findViewById(R.id.tv_MenuName);
  717. tv_MenuQty = (TextView) itemView.findViewById(R.id.tv_MenuQty);
  718. tv_MenuPrice = (TextView) itemView.findViewById(R.id.tv_MenuPrice);
  719. }
  720. }
  721. }