@Override
  public void pauseView() {
    try {
      CrashReporter.leaveBreadcrumb("Trip_Stock_Load: pauseView");

      // Pause updating.
      infoview.pause();
    } catch (Exception e) {
      CrashReporter.logHandledException(e);
    }
  }
        @Override
        public void onClick(View paramView) {
          String errorMessage = "";
          int litres = 0;

          try {
            // Leave breadcrumb.
            CrashReporter.leaveBreadcrumb("Trip_Stock_Load: onOK");

            // Check for product.
            if (product == null) {
              errorMessage = "Please select a product";
              return;
            }

            // Check loaded quantity.
            try {
              litres = decimalFormat.parse(etLoaded.getText().toString()).intValue();
            } catch (ParseException e) {
              e.printStackTrace();
            }

            if (litres <= 0) {
              errorMessage = "Litres missing";
              return;
            }

            // Update stock locally.
            Active.vehicle.recordLoad(product, litres);

            // Update stock on server.
            trip.sendVehicleStock();

            // Reset UI.
            etLoaded.setText("");

            // Notify user.
            Toast t = Toast.makeText(trip, litres + " loaded", Toast.LENGTH_SHORT);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();
          } catch (Exception e) {
            CrashReporter.logHandledException(e);
          } finally {
            // Show error message?
            if (errorMessage.length() > 0) {
              Toast t = Toast.makeText(trip, errorMessage, Toast.LENGTH_SHORT);
              t.setGravity(Gravity.CENTER, 0, 0);
              t.show();
            }
          }
        }
  private void getRequiredProducts() {
    CrashReporter.leaveBreadcrumb("Trip_Stock_Load: getRequiredProducts");

    // Create the Hashtable if it does not already exist
    if (requiredProducts == null) {
      requiredProducts = new Hashtable<String, Integer>();
    }

    // Empty it
    requiredProducts.clear();

    if (Active.trip != null) {
      // Get all undelivered orders in the trip
      for (dbTripOrder order : Active.trip.getUndelivered()) {
        // Get all the order lines in each order
        for (dbTripOrderLine orderLine : order.getTripOrderLines()) {
          if (orderLine.Product == null || orderLine.Product.MobileOil == 3) {
            continue;
          }

          String productName = orderLine.Product.Desc;
          int orderQuantity = orderLine.OrderedQty;

          if (!requiredProducts.containsKey(productName)) {
            requiredProducts.put(productName, 0);
          }

          requiredProducts.put(productName, requiredProducts.get(productName) + orderQuantity);
        }
      }
    }
  }
        @Override
        public void onClick(View paramView) {
          try {
            // Leave breadcrumb.
            CrashReporter.leaveBreadcrumb("Trip_Stock_Load: onCancel");

            if (btnCancel.getText().equals("Close")) {
              // Close view.
              btnCancel.setEnabled(false);

              // Switch back to previous view.
              trip.selectView(previousViewName, -1);
            } else {
              // Cancel input.
              etLoaded.setText("");
            }
          } catch (Exception e) {
            CrashReporter.logHandledException(e);
          }
        }
  @SuppressLint("SetTextI18n")
  @Override
  public void updateUI() {
    try {
      CrashReporter.leaveBreadcrumb("Trip_Stock_Load : updateUI");

      // Update the UI.
      infoview.setDefaultTv1("Load product");

      // Set the Line product in the title bar
      infoview.setDefaultTv2(DbUtils.getInfoviewLineProduct(Active.vehicle.getHosereelProduct()));

      if (product == null) {
        tvProduct.setText("None");
      } else {
        int stockLevel = 0;

        if (stockLevels.containsKey(product.Desc)) {
          stockLevel = stockLevels.get(product.Desc);
        }

        int requiredAmount = 0;

        if (requiredProducts.containsKey(product.Desc)) {
          requiredAmount = requiredProducts.get(product.Desc);
        }

        if (requiredAmount > stockLevel) {
          int toLoad = requiredAmount - stockLevel;

          // Load product.
          tvProduct.setText(String.format(Locale.UK, "%s %d litres", product.Desc, toLoad));
        } else {
          // Load product.
          tvProduct.setText(String.format(Locale.UK, "%s 0 litres", product.Desc));
        }
      }
    } catch (Exception e) {
      CrashReporter.logHandledException(e);
    }
  }
  private void init(Context context) {
    try {
      // Leave breadcrumb.
      CrashReporter.leaveBreadcrumb("Trip_Stock_Load: init");

      // Store reference to Trip activity.
      trip = (Trip) context;

      // Setup a standard decimal format.
      decimalFormat = new DecimalFormat("#,##0");

      // Inflate layout.
      LayoutInflater inflater =
          (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      inflater.inflate(R.layout.trip_stock_load, this, true);

      // Find UI controls.
      infoview = (MyInfoView1Line) this.findViewById(R.id.trip_stock_load_infoview);

      etLoaded = (MyEditText) this.findViewById(R.id.trip_stock_load_litres);

      tvProduct = (TextView) this.findViewById(R.id.trip_stock_load_product);

      Button btnChange = (Button) this.findViewById(R.id.trip_stock_load_change);

      btnOK = (Button) this.findViewById(R.id.trip_stock_load_ok);

      btnCancel = (Button) this.findViewById(R.id.trip_stock_load_cancel);

      etLoaded.addTextChangedListener(onLitresChanged);

      btnChange.setOnClickListener(onChange);
      btnOK.setOnClickListener(onOK);
      btnCancel.setOnClickListener(onCancel);
    } catch (Exception e) {
      CrashReporter.logHandledException(e);
    }
  }
  private void validate() {
    try {
      CrashReporter.leaveBreadcrumb("Trip_Stock_Load: validate");

      int litres = 0;

      // Check if value is valid.
      try {
        String text = etLoaded.getText().toString();

        if (text.length() > 0) {
          litres = decimalFormat.parse(text).intValue();
        }
      } catch (ParseException e) {
        e.printStackTrace();
      }

      btnOK.setEnabled(litres > 0);
      btnCancel.setText(litres > 0 ? "Cancel" : "Close");
    } catch (Exception e) {
      CrashReporter.logHandledException(e);
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    mContext = getActivity().getApplicationContext();
    mCrashReporter = CrashReporter.setup(mContext);
    mIntegrationType = getArguments().getString(EXTRA_INTEGRATION_TYPE);
    mAuthorization = getArguments().getParcelable(EXTRA_AUTHORIZATION_TOKEN);

    if (mHttpClient == null) {
      mHttpClient = new BraintreeHttpClient(mAuthorization);
    }

    if (savedInstanceState != null) {
      List<PaymentMethodNonce> paymentMethodNonces =
          savedInstanceState.getParcelableArrayList(EXTRA_CACHED_PAYMENT_METHOD_NONCES);
      if (paymentMethodNonces != null) {
        mCachedPaymentMethodNonces.addAll(paymentMethodNonces);
      }

      mHasFetchedPaymentMethodNonces =
          savedInstanceState.getBoolean(EXTRA_FETCHED_PAYMENT_METHOD_NONCES);
      mIsBrowserSwitching = savedInstanceState.getBoolean(EXTRA_BROWSER_SWITCHING);
      mSessionId = savedInstanceState.getString(EXTRA_SESSION_ID);
    } else {
      mSessionId = DeviceMetadata.getFormattedUUID();
      if (mAuthorization instanceof TokenizationKey) {
        sendAnalyticsEvent("started.client-key");
      } else {
        sendAnalyticsEvent("started.client-token");
      }
    }

    fetchConfiguration();
    mCrashReporter.sendPreviousCrashes(this);
  }
        @Override
        public void onClick(View paramView) {
          try {
            // Leave breadcrumb.
            CrashReporter.leaveBreadcrumb("Trip_Stock_Load: onChange");

            // Check there are products.
            if (!products.isEmpty()) {
              int index = -1;

              if (product != null) {
                // Find currently selected product.
                for (int i = 0; i < products.size(); i++) {
                  if (products.get(i).getId().equals(product.getId())) {
                    index = i;

                    break;
                  }
                }
              }

              // Move to next product.
              index++;

              // Change to next product.
              product = index != products.size() ? products.get(index) : null;

              // Validate.
              validate();

              // Reflect changes on UI.
              updateUI();
            }
          } catch (Exception e) {
            CrashReporter.logHandledException(e);
          }
        }
  @SuppressLint("SetTextI18n")
  @Override
  public boolean resumeView() {
    try {
      CrashReporter.leaveBreadcrumb("Trip_Stock_Load: resumeView");

      // Clear product.
      product = null;

      // Load products.
      products = dbProduct.getAllMeteredAndNonMetered();

      // Resume updating.
      infoview.resume();

      // Clear litres & focus.
      etLoaded.setText("");
      etLoaded.requestFocus();

      // Reset buttons.
      btnOK.setEnabled(false);
      btnCancel.setText("Close");
      btnCancel.setEnabled(true);

      // Make sure that the required products Hashtable is populated
      getRequiredProducts();

      // Make sure that the stock levels Hashtable is populated
      getStockLevels();

      return true;
    } catch (Exception e) {
      CrashReporter.logHandledException(e);
      return false;
    }
  }
  private void getStockLevels() {
    CrashReporter.leaveBreadcrumb("Trip_Stock_Load: getStockLevels");

    // Create the Hashtable if it does not already exist
    if (stockLevels == null) {
      CrashReporter.leaveBreadcrumb(
          "Trip_Stock_Load: getStockLevels - Creating stock levels hashtable ...");

      stockLevels = new Hashtable<String, Integer>();
    }

    CrashReporter.leaveBreadcrumb(
        "Trip_Stock_Load: getStockLevels - Clearing stock levels hashtable ...");

    // Empty it
    stockLevels.clear();

    for (dbVehicleStock vehicleStock : dbVehicleStock.findAllNonCompartmentStock(Active.vehicle)) {
      String productName = vehicleStock.Product.Desc;
      int stockLevel = vehicleStock.CurrentStock;

      if (!stockLevels.containsKey(productName)) {
        CrashReporter.leaveBreadcrumb(
            String.format(
                "Trip_Stock_Load: getStockLevels - Adding entry for %s to hashtable ...",
                productName));

        stockLevels.put(productName, 0);
      }

      CrashReporter.leaveBreadcrumb("Trip_Stock_Load: getStockLevels - Updating stock level ...");

      stockLevels.put(productName, stockLevels.get(productName) + stockLevel);
    }

    if (Active.vehicle.getHasHosereel()) {
      CrashReporter.leaveBreadcrumb(
          "Trip_Stock_Load: getStockLevels - Adding hosereel product to stock");

      String productName = Active.vehicle.getHosereelProduct().Desc;
      int hosereelCapacity = Active.vehicle.getHosereelCapacity();

      if (!stockLevels.containsKey(productName)) {
        stockLevels.put(productName, 0);
      }

      stockLevels.put(productName, stockLevels.get(productName) + hosereelCapacity);
    }
  }
  @Override
  public void onDestroy() {
    super.onDestroy();

    mCrashReporter.tearDown();
  }