• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Local application takes too long to process items from database

Deemar

Newbie
Feb 7, 2012
38
2
Hi, I have built an application where the user can enter some information and it will generate an on screen quote, automatically refreshing it as they modify each input. Currently it needs to work without internet so I'm synchronizing the database as connectivity is available and I'm running the quoting process from the products stored in the local database.

My problem is each time the quote is generated, it has to loop through 1000 items, generate a quantity for each one, then calculate a price, add it all together and display it on the quote. This is currently taking 1 second to accomplish with just 5 items, I need to enter all 1000. I'm afraid it's going to be very long with all products in the database.

With the web based application we're using until this is ready, it offloads all processing to the server so it comes back in under a second after processing all 1000 items but offloading that process to the cloud is not an option when running a local Android application on a tablet without internet. Is my only option to buy a really high end tablet that can process it much faster? Do they exist?

The database is NoSQL. Thanks.
 
So 90% of the time sink is calculating the price. Here is the function which loops through all 1000 materials, figures out how that particular material is calculated and then does the calculation. Right now I've only written the code for Price x Quantity but there are 8 different types of calculations.
Java:
public Double calculateQuotePrice()
    {
        // this simply calculates the price of the new quote
        Double price = 0.0;
        JSONObject materials;
        JSONObject material;
     //   String columnPrice = "price";
        String columnPrice = "unit_price";
        String columnId = "product_id";
        String columnCalculationId = "total_price_calculation_id";

        // on initial page load this will not be set
        if (getMaterials() == null) {
            // retrieve saved price from database if we're loading a saved quote
            return getPrice();
        }

        try {
            // create JSON object from JSON string
            materials = new JSONObject(getMaterials()); // returns JSON string of all materials and attributes

            Iterator<String> keys = materials.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                Object v = materials.get(key);
                material = new JSONObject(v.toString());

                // for each material, get the calculation type and find the total price
                // different materials have prices calculated in different ways
                switch(material.getInt(columnCalculationId)){
                    case 0:
                        // report error
                        break;
                    case 1: // Q x P
                        int quantity = getQuantityOfProduct(material.getInt(columnId));
                        double unitPrice =
                            Double.parseDouble(material.getString(columnPrice)
                                .replace("[", "")
                                .replace("]", "")
                                .replace("\"", ""));
                        price += quantity * unitPrice;
                        break;
                    case 2: // lumber
                        break;
                    case 3: // P x W x L x Q
                        break;
                    default:
                        break;
                }

            }

        } catch (JSONException e) {
            // Something went wrong!
            System.out.println("asdf error in calculateQuotePrice: " + e.toString());
        }

        return price;
    }

And this here gets the quantities which are used in the function above. My mistake, I have 13 items, not 5. I added some comments for the first item, 3x5 windows. It has to get the JSON string from the quote model, parse it, then loop through each window to make sure it isn't set to "customer supplied," then set the quantity if necessary.

Java:
public int getQuantityOfProduct(int productId) throws JSONException {
        int quantity = 0;
        int squareFootage = 0;
        JSONArray items = null;

        //      System.out.println("Asdf product: " + productId);

        switch (productId) {
            case 1: // 3x5 fixed window
                try {
                    JSONArray windows = new JSONArray(getWindows());
                    // loop through each window the user added to the building
                    for (int i = 0; i < windows.length(); i++) {
                        // deal with one window at a time
                        JSONObject window = windows.getJSONObject(i);
                        // if the window is set to customer supplied, it is a zero quantity
                        if (window.getString("customer_supplied") != "true" && window.getInt("type") == 1)
                            quantity += Integer.parseInt(window.getString("quantity"));
                    }
                } catch (JSONException e) {
                    System.out.println("Asdf error: " + e.toString());
                    e.printStackTrace();
                    return 0;
                }
                break;
            case 2: // quality management
                quantity = getMaterialOnly() ? 0 : 1;
                break;
            case 3: // custom materials
                // create JSON object from JSON string
                try {
                    JSONArray customs = new JSONArray(getCustoms());
                    for (int i = 0; i < customs.length(); i++) {
                        JSONObject custom = customs.getJSONObject(i);
                        if (custom.getString("included") == "true")
                            quantity += Integer.parseInt(custom.getString("materials"));
                    }
                } catch (JSONException e) {
                    System.out.println("Asdf error: " + e.toString());
                    e.printStackTrace();
                    return 0;
                }
                break;
            case 4: // custom labour
                if (getMaterialOnly())
                    break;

                // create JSON object from JSON string
                try {
                    JSONArray customs = new JSONArray(getCustoms());
                    for (int i = 0; i < customs.length(); i++) {
                        JSONObject custom = customs.getJSONObject(i);
                        if (custom.getString("included") == "true")
                            quantity += Integer.parseInt(custom.getString("labour"));
                    }
                } catch (JSONException e) {
                    System.out.println("Asdf error: " + e.toString());
                    e.printStackTrace();
                    return 0;
                }
                break;
            case 5: // peak sign
                quantity = 2;
                break;
            case 6: // exterior height labour premium
                if (getMaterialOnly())
                    break;

                if (getBuildingHeight() >= 16)
                    quantity = ((getBuildingHeight() - 16) / 2) * getBuildingWidth() * getBuildingLength();
                break;
            case 7: // interior height labour premium
                if (getInsulated() && getBuildingHeight() >= 16 && !getMaterialOnly())
                    quantity = ((getBuildingHeight() - 16) / 2) * getInsulationWidth() * getInsulationLength();
                break;
            case 8: // 3/4" Plywood
                int osbSquareFootagePerSheet = 16;
                JSONArray foldingDoors = new JSONArray(getFoldingDoors());
                for (int i = 0; i < foldingDoors.length(); i++) {
                    JSONObject door = foldingDoors.getJSONObject(i);
                    if (door.getString("shear-wall") == "true")
                        quantity = door.getInt("quantity") * (getBuildingWidth() - door.getInt("width")) * getBuildingHeight() / osbSquareFootagePerSheet;
                }
                break;
            case 9: // Shear Wall Labour
                if (getMaterialOnly())
                    break;

                items = new JSONArray(getFoldingDoors());
                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    if (item.getString("shear-wall") == "true")
                        quantity += item.getInt("quantity") * (getBuildingWidth() - item.getInt("width")) * getBuildingHeight();
                }
                break;
            case 10: // exterior labour 8600+
                if (getMaterialOnly())
                    break;

                squareFootage = getBuildingWidth() * getBuildingLength();
                quantity += squareFootage >= 8600 ? squareFootage : 0;
                break;
            case 11: // interior labour 8600+
                if (getMaterialOnly())
                    break;

                squareFootage = getInsulationWidth() * getInsulationLength();
                quantity += squareFootage >= 8600 ? squareFootage : 0;
                break;
            case 12: // X-Tension Straps
                JSONObject inputs = new JSONObject(getInputs());
                if (inputs.getString("x-tension-quantity").equals("") || inputs.getString("x-tension-quantity").equals("0"))
                {
                    quantity += getBuildingHeight() >= 16 ? 4 : 0;
                    if (inputs.getString("x-tension").equals("true"))
                    {
                        items = new JSONArray(getFoldingDoors());
                        for (int i = 0; i < items.length(); i++) {
                            JSONObject item = items.getJSONObject(i);
                            if (item.getString("shear-wall").equals("true"))
                                quantity -= 2 * item.getInt("quantity");
                        }
                    }
                }
                else
                    quantity += Integer.parseInt(inputs.getString("x-tension-quantity"));

                quantity = Math.max(quantity, 0);
                break;
            case 13: // poly carbonate panel
                items = new JSONArray(getFoldingDoors());
                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    if (item.getString("poly-carbonate").equals("true"))
                        quantity += item.getInt("quantity") * item.getInt("width");
                }
                break;
            case 14:
                quantity = 1;
                break;
            case 284:
                quantity = 3;
                break;
            default:
                quantity = 0;
                break;
        }

        return quantity;
    }

There will be a total of 12XX items we use to make the buildings.
 
Upvote 0
Wow, that's very cool! I ran it and it sat at 0% for CPU, 4 B/s for network and 71 MB / 128 for memory with no change when I checked the box on the page that reloads the quote.

I did run a timer in the code to see where the time was going and it looks like every product that gets a price takes about 1 millisecond. Therefore, for 12XX products, it's taking about a second which is completely fine but I'm worried that will increase once I add the quantity calculations for all of them. Right now only 13 are calculating quantities, the others are just blazing through the switch statement without calculating anything because I haven't entered them yet.

It's also a problem that it runs on the main thread when I check the checkbox because the box check animation doesn't actually run until the price is returned so the user doesn't see the box get checked for about 1 second. That's a really long time for user interaction.
 
Upvote 0
Yes, I was mistaken and it's actually 13 items. So it's looping through the switch statement 12XX times, once for each item, but there are only cases in there for 13 of the items so the other 1200 or so are just going through the switch statement without calculating any quantity at all at the moment. I need to add the quantity calculations for those.

You can see it in the code I posted, there are only 13 cases in the switch statement for getting the quantities. Every item after item 13 is looping through the switch statement without actually doing anything, I'm assuming it's going to increase the time when they actually have to stop and calculate quantities instead of just dumping into the default case.
 
Upvote 0
Now I'm confused. You said initially there were only 5 items in the database. Now you're saying there are 1200?

Performance problems like this often aren't easy to track down. That's why using a profiler like the one above, can really help.
There's nothing in the code you've given that would hold things up a great deal. So that means the delay is caused by something else. And as we haven't seen the surrounding code which calls the fragments you've listed, it's possible the problems lies elsewhere. In particular, we haven't seen how your data is retrieved from the database. DB access can often cause a huge bottleneck in software, particularly if the queries used aren't efficient.
 
Upvote 0
Sorry, there are 1200 items in the database, each one loops through the price function, which then loops through the quantity function, since the quantity is required to get the total price.

I have only put 13 of the 1200 quantity calculations into the function so far, it takes a long time to write them. So it is looping through 1200 times but right now only 13 items are getting calculations, the others are simply rolling through the switch statement and getting to the end without calculating anything.

So, on loops 1-13, it calculates quantities for the products being requested, then for the next ~1200 items, they still loop through but won't calculate anything until I can write the quantity calculations for them. They're in the web platform, I just have to convert them to Java for Android.
 
Upvote 0
So I see lines like this in your code

Code:
JSONArray windows = new JSONArray(getWindows());

I assume that's retrieving your data from the DB. How's that working, and how long does it take?

And are you calling this method

Code:
public int getQuantityOfProduct(int productId) throws JSONException {

for all possible productIds?

You see you just haven't given enough code for a meaningful reply to your question.
 
Upvote 0
Sorry about that.

On initial load of the view, I get the entire list of items from the database, create a hashmap, insert all items, convert it to a JSON string and call setMaterials on the quote model to give it one single JSON string with all the item information. Once I have the huge JSON string of all items and their attributes, I pull the windows out and call setWindows() so the quote model then has a list of all windows in it. I do the same for doors and any other item I have on that quote.

By the time I click a checkbox to change one of the inputs and get a new price, this is already completed and now I don't need to connect to the database again as long as I'm working with the quote. The getWindows() function simply asks the quote model for the JSON string of windows and their attributes so I can convert them to a JSONArray, loop through them, check if they were set to customer supplied and then add the quantity to the total item quantity. Once I have all the windows on that quote, I return those as the total quantity for that item ID.

So no, getWindows() does not contact the database, it just gets the JSON string from the model which was populated from the database on the initial creation of the view. This is done by the time I need to interact with the quote inputs. This database call only happens once and is actually done asynchronously so it doesn't hold up the loading of the view initially.

Yes, I do call getQuantityOfProduct() for every individual product I'm requesting a quantity. I call it on a loop when I'm retrieving the total quote price or I could call it for a single item if I want to display the number of screws / fasteners / doors as a BOM (Bill Of Materials) on the quote.
 
Upvote 0
No, not at all, it's just huge. The web version is a few hundred thousand lines of code, probably over a million total. It doesn't just quote, it automatically creates purchase orders, pick lists, login, database services, synchronization services, job mapping, reporting and much more.

Here is the QuoteViewFragment file, how much of the whole program do you want me to paste here? I'm just in the process of converting the huge web application to a mobile application so it's not as huge yet and I'm also learning Android as I go so feel free to point out a thousand things I'm doing incorrectly. I can post anything else you need, maybe even every file if you want it.

As a bit of background on when this file runs, the user is presented with a RecyclerView of quotes and when they select one, it passes some of the chosen quote values through the Intent. Then the chosen quote loads for the customer and they can view and edit it. It's a screen with 5 different fragments, each one can be swiped left or right and they consist of:
1. a page where they can see everything the quote contains, with input boxes and checkboxes so they can modify it.
2. a page where they see how the quote will look once sent to the customer
3. a page where they can make meta modifications like adding a deposit or GPS information which won't display on the quote.
4. blank page for now
5. the contract which looks slightly different from the quote since it has some terms and conditions, plus a place to sign.

That's why I use fragments.

The line that hangs for 1 second below is:
Double quotePriceValue = quote.calculateQuotePrice();

Java:
package com.example.android.basicsyncadapter.quotesFragments;


import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.SyncResult;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.example.android.basicsyncadapter.QuoteDetailsActivity;
import com.example.android.basicsyncadapter.R;
import com.example.android.basicsyncadapter.model.Quote;
import com.example.android.basicsyncadapter.model.User;
import com.example.android.basicsyncadapter.net.FeedParser;
import com.example.android.basicsyncadapter.provider.MaterialsContract;
import com.example.android.basicsyncadapter.provider.QuoteMaterialsContract;
import com.example.android.basicsyncadapter.provider.UserContract;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.example.android.basicsyncadapter.quotesRecycler.QuoteListAdapter.getCurrentLocale;

public class QuoteViewFragment extends Fragment {

    private NumberFormat defaultFormat;
    private static final String quoteMaterialsTableName = "match_quote_product";

    /**
     * Project used when querying content provider. Returns all known fields.
     */
    private static final String[] QUOTE_MATERIALS_PROJECTION = new String[] {
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry._ID,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_ENTRY_ID,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_QUOTE_ID,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_PRODUCT_ID,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_WIDTH,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_LENGTH,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_HEIGHT,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_LOCATION,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_QUANTITY,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_LOCKING_HANDLE_SIDE,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_POWER,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_INSULATED,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_CUSTOMER_SUPPLIED,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_STOREY,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_WINDOW_INSERTS,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_BOARD_FEET,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_PRICE_PER_K,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_UNIT_PRICE,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_COMMISSION_SPIFF,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_MARKUP_SPIFF,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_COMMISSION_SPIFF,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_MARKUP_SPIFF,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_PRICE_CALCULATION_ID,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_PURCHASE_ORDER_ID,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_COLOUR_TYPE_ID,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_GROUP_PRICES,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_PRICE,
        quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_UNIT_OF_MEASURE
    };

    String customerNameText;
    TextView customerName;
    TextView quoteNumber;
    TextView quoteDate;
    TextView quoteExpiry;
    TextView quotePrice;
    TextView quotePrice2;
    TextView buildingDetails;
    TextView buildingClassification;
    TextView trussDescription;
    TextView strappingDescription;
    TextView metalDescription;
    TextView ridgeDescription;
    TextView stormBracketDescription;
    TextView blueprintsDescription;
    TextView wallDescription;
    TextView ceilingInsulationDescription;
    TextView insulationSectionHeader;
    TextView upgradePrice3PlyPerma;
    TextView upgradePrice4PlyPerma;
    TextView upgradePrice8400Perma;

    LinearLayout quoteInsulationSection;
    LinearLayout quoteInsulationSubsection;
    LinearLayout warrantySection;

    TableLayout optionsTable;
    TableLayout upgradesTable;

    TableRow upgradeRow3PlyPerma;
    TableRow upgradeRow4PlyPerma;
    TableRow upgradeRow8400Perma;

    Quote quote;
    Long startTime;

    public QuoteViewFragment() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        Intent intent = getActivity().getIntent();
        quote = (Quote) intent.getSerializableExtra("quote");
        LoadQuoteValuesAsynchronously quoteValueLoader = new LoadQuoteValuesAsynchronously(this, getContext().getContentResolver(), quote, startTime);
        quoteValueLoader.execute();
    }

    public void loadQuoteValues()
    {
        Double quotePriceValue = quote.calculateQuotePrice();

        // remove all views before populating the view again
        optionsTable.removeAllViews();
        buildingDetails.setText(String.valueOf(quote.getBuildingWidth()) + "' X " + String.valueOf(quote.getBuildingLength() + "' X " + String.valueOf(quote.getBuildingHeight() + "' " + quote.getBuildingType())));
        quotePrice.setText(String.valueOf(defaultFormat.format(quotePriceValue)));
        quotePrice2.setText(String.valueOf(defaultFormat.format(quotePriceValue)));
        buildingClassification.setText("• " + quote.getOccupancy() + " Occupancy Classification");
        trussDescription.setText("• " + quote.getEvePostSpacing() + "' O/C Engineered Trusses" + (quote.getDoublePlyRafters() ? ", Double Ply" : ""));
        metalDescription.setText("• Premium 29 gauge Hi-Tensile FC36 profile metal including a 3/4\" rib");
        ridgeDescription.setText("• " + quote.getRidge());
        quoteNumber.setText("Quote: " + quote.getNumber());
        quoteExpiry.setText(formatDate(quote.getQuotedDate(), 14));
        if (quote.getStormBrackets())
            stormBracketDescription.setText("• Storm Brackets");
        if (quote.getBlueprints())
            blueprintsDescription.setVisibility(View.VISIBLE);
        else
            blueprintsDescription.setVisibility(View.GONE);
        wallDescription.setText("• " + quote.getEvePostSpacing() + "' O/C " + quote.getWallType().replace("&#039;", "'").replace("&quot;", "\"") + (quote.getPostDiscs() ? " with Post Disc" : ""));
        ceilingInsulationDescription.setText("• R40 Ceiling Insulation");
        if (quote.getInsulated()) {
            quoteInsulationSection.setVisibility(View.VISIBLE);
            quoteInsulationSubsection.setVisibility(View.VISIBLE);
            insulationSectionHeader.setText("Insulation Package: " + quote.getInsulationWidth() + "' X " + quote.getInsulationLength() + "'");
        }

        if (quote.getWarranty5())
            warrantySection.setVisibility(View.VISIBLE);

        // get currency locale for proper formatting
        NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(getCurrentLocale(getContext()));
        quoteDate.setText(formatDate(quote.getQuotedDate(), 0));

        // if any upgrade options were selected, show the table
        if (
            quote.get3PlyPermaPostUpgrade()
                || quote.get4PlyPermaPostUpgrade()
                || quote.get8400PermaPostUpgrade()
        )
            upgradesTable.setVisibility(View.VISIBLE);

        if (quote.get3PlyPermaPostUpgrade()) {
            upgradePrice3PlyPerma.setText("$ ");
            upgradeRow3PlyPerma.setVisibility(View.VISIBLE);
        }

        if (quote.get4PlyPermaPostUpgrade()) {
            upgradePrice4PlyPerma.setText("$ ");
            upgradeRow4PlyPerma.setVisibility(View.VISIBLE);
        }

        if (quote.get8400PermaPostUpgrade()) {
            upgradePrice8400Perma.setText("$ ");
            upgradeRow8400Perma.setVisibility(View.VISIBLE);
        }

        try {
            // json string coming in is contained inside square brackets
            // assigning to a JSONArray and then JSONObject removes these brackets
            JSONArray overheadList = new JSONArray(quote.getOverheadDoors());
            JSONArray slidingList = new JSONArray(quote.getSlidingDoors());
            JSONArray foldingList = new JSONArray(quote.getFoldingDoors());
            JSONArray manDoorList = new JSONArray(quote.getManDoors());
            JSONArray windowList = new JSONArray(quote.getWindows());
            JSONArray customWindowList = new JSONArray(quote.getCustomWindows());
            JSONArray wallLightList = new JSONArray(quote.getWallLights());
            JSONArray kickWallList = new JSONArray(quote.getKickWall());
            JSONArray partitionWallList = new JSONArray(quote.getPartitionWalls());
            JSONArray mezzanineList = new JSONArray(quote.getMezzanines());
            JSONArray leanToList = new JSONArray(quote.getLeanTos());
            JSONArray customsList = new JSONArray(quote.getCustoms());

            // add overhead doors to the quote options list
            for (int i = 0; i < overheadList.length(); i++) {
                // get each overhead door
                JSONObject jsonDoors = (JSONObject)overheadList.get(i);
                System.out.println("asdf door operator: " + jsonDoors.getString("operator"));
                String overheadWindowQuantity = jsonDoors.get("window_inserts").toString();
                String overheadDescription =
                        jsonDoors.getString("customer_supplied").equals("true") ?
                                "Prepared " + jsonDoors.getString("location") + " " + jsonDoors.getString("width") + "' x " + jsonDoors.getString("height") + "' Opening"
                                : jsonDoors.getString("width") + "' X " + jsonDoors.getString("height") + "' Overhead Door";
                createQuoteOptionRow(
                        jsonDoors.getString("quantity"),
                        overheadDescription +
                        (jsonDoors.getString("customer_supplied").equals("true") ? "" : ", " + jsonDoors.getString("location")) +
                        (jsonDoors.getString("operator").equals("None") ? "" : ", " + jsonDoors.getString("operator")) + // use getString because it's pulling from the model, not the input
                        (jsonDoors.getString("bow_strap").equals("true") ? ", Bow Strap" : "") +
                        (overheadWindowQuantity.equals("") ? "" : ", " + overheadWindowQuantity + " Window Insert" + (Integer.parseInt(overheadWindowQuantity) > 1 ? "s" : "") + " Per Door"),
                    quote,
                    optionsTable
                );
            }

            // add sliding doors to the quote options list
            for (int i = 0; i < slidingList.length(); i++) {
                // get each sliding door
                JSONObject jsonDoors = (JSONObject)slidingList.get(i);
                createQuoteOptionRow(jsonDoors.getString(
                    "quantity"),
                    jsonDoors.getString("width") +
                        "' X " + jsonDoors.getString("height") +
                        ", " +
                        "Sliding Door" +
                        "' " +
                        jsonDoors.getString("location"),
                    quote,
                    optionsTable
                );
            }

            // add folding doors to the quote options list
            for (int i = 0; i < foldingList.length(); i++) {
                // get each folding door
                JSONObject jsonDoors = (JSONObject)foldingList.get(i);
                createQuoteOptionRow(
                    jsonDoors.getString("quantity"),
                    jsonDoors.getString("width") +
                        "' X " +
                        jsonDoors.getString("height") +
                        "' " +
                        "Bi-Fold Door" +
                        (jsonDoors.getString("lock").equals("None") ? "" :
                                jsonDoors.getString("lock").equals("Left") || jsonDoors.getString("lock").equals("Right") ?
                                    ", " + jsonDoors.getString("lock") + " Side Handle" :
                                    ", " + jsonDoors.getString("lock") + " With Remote") +
                        ", " +
                        jsonDoors.getString("insulated") +
                        " Insulation, " +
                        jsonDoors.getString("windows") +
                        " Windows Per Door" +
                        (jsonDoors.getBoolean("column_supports") ? ", Column Supports": "") +
                        (jsonDoors.getBoolean("jtrack") ? ", J Track": "") +
                        ", With Double Truss" +
                        (jsonDoors.getBoolean("shear-wall") ? ", With Shear Wall Package" : ""),
                    quote,
                    optionsTable
                );
            }

            // add gable vents to the quote options list
            if (quote.getGableVents() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getGableVents()),
                        "Gable Vents",
                        quote,
                        optionsTable
                );

            // add x-tension straps to the quote options list
            if (quote.getXTensionStrapQuantity() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getXTensionStrapQuantity()),
                        "X-Tension Straps",
                        quote,
                        optionsTable
                );

            // add storm brackets to the quote options list
            if (quote.getStormBracketQuantity() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getStormBracketQuantity()),
                        "Storm Brackets",
                        quote,
                        optionsTable
                );

            // add man doors to the quote options list
            for (int i = 0; i < manDoorList.length(); i++) {
                // get each
                JSONObject itemList = (JSONObject)manDoorList.get(i);

                createQuoteOptionRow(
                        itemList.getString("quantity"),
                        getNameFromMaterialId(itemList.getInt("type")) +
                                (itemList.getInt("storey") == 1 ? ", 2nd Storey" : ""),
                        quote,
                        optionsTable
                );
            }

            // add windows to the quote options list
            for (int i = 0; i < windowList.length(); i++) {
                // get each
                JSONObject itemList = (JSONObject)windowList.get(i);

                createQuoteOptionRow(
                        itemList.getString("quantity"),
                        getNameFromMaterialId(itemList.getInt("type")) +
                                (itemList.getInt("storey") == 1 ? ", 2nd Storey" : ""),
                        quote,
                        optionsTable
                );
            }

            // add custom windows to the quote options list
            for (int i = 0; i < customWindowList.length(); i++) {
                // get each
                JSONObject itemList = (JSONObject)customWindowList.get(i);

                createQuoteOptionRow(
                        itemList.getString("quantity"),
                        itemList.getString("width") +
                                "'x" +
                                itemList.getString("height") +
                                "' " +
                                itemList.getString("type") +
                                " " +
                                itemList.getString("pane") +
                                " Custom Window",
                        quote,
                        optionsTable
                );
            }

            // add wall light to the quote options list
            for (int i = 0; i < wallLightList.length(); i++) {
                // get each
                JSONObject itemList = (JSONObject)wallLightList.get(i);

                createQuoteOptionRow(
                        itemList.getString("quantity"),
                        itemList.getInt("length") +
                                "' of " +
                                itemList.getInt("height") +
                                "' High " +
                                itemList.getString("location") +
                                " Wall Light",
                        quote,
                        optionsTable
                );
            }

            // add gable vents to the quote options list
            if (quote.getGableVents() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getGableVents()),
                        "Gable Vents",
                        quote,
                        optionsTable
                );

            // add kick wall to the quote options list
            for (int i = 0; i < kickWallList.length(); i++) {
                // get each
                JSONObject itemList = (JSONObject)kickWallList.get(i);

                createQuoteOptionRow(
                        "1", // always 1
                        itemList.getInt("length") +
                                "' of " +
                                itemList.getInt("height") +
                                "' High " +
                                itemList.getString("location") +
                                " Kick Wall",
                        quote,
                        optionsTable
                );
            }

            // add eve soffit to the quote options list
            if (quote.getEveSoffitLength() > 0)
                createQuoteOptionRow(
                        "1",
                        quote.getEveSoffitLength() +
                                "' of Eve Soffit",
                        quote,
                        optionsTable
                );

            // add gable soffit to the quote options list
            if (quote.getGableSoffitLength() > 0)
                createQuoteOptionRow(
                        "1",
                        quote.getGableSoffitLength() +
                                "' of Gable Soffit",
                        quote,
                        optionsTable
                );

            // add smoke stop to the quote options list
            if (quote.getSmokeStops() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getSmokeStops()),
                        "Smoke Stop",
                        quote,
                        optionsTable
                );

            // add gable stop to the quote options list
            if (quote.getGableStops() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getGableStops()),
                        "Gable Stop",
                        quote,
                        optionsTable
                );

            // add fire stop to the quote options list
            if (quote.getFireStops() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getFireStops()),
                        "Fire Stop",
                        quote,
                        optionsTable
                );

            // this might not be set yet
//            if (quote.getMaterials() != null) {
                int smokeDamperQuantity = quote.getQuantifyOfQuoteProduct(quote.SMOKE_DAMPERS);
       //         int smokeDamperQuantity = getItemQuantity(quote.SMOKE_DAMPERS, quote.getQuoteId());

                if (smokeDamperQuantity > 0)
                    createQuoteOptionRow(String.valueOf(smokeDamperQuantity), "Smoke Damper" + (smokeDamperQuantity > 1 ? "s" : ""), quote, optionsTable);
       //     }

            // add drift load rafters to the quote options list
            if (quote.getDriftLoadRafters() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getDriftLoadRafters()),
                        "Drift Load Rafters",
                        quote,
                        optionsTable
                );

            // add attic hatches to the quote options list
            if ((quote.getAtticHatches() + quote.getAdditionalAtticHatches()) > 0)
                createQuoteOptionRow(
                        String.valueOf((quote.getAtticHatches() + quote.getAdditionalAtticHatches())),
                        "Attic Hatches",
                        quote,
                        optionsTable
                );

            // add mezzanine to the quote options list
            for (int i = 0; i < mezzanineList.length(); i++) {
                // get each
                JSONObject itemList = (JSONObject)mezzanineList.get(i);

                createQuoteOptionRow(
                        "1", // always 1
                        itemList.getInt("width") +
                                "' x " +
                                itemList.getInt("width") +
                                "' Mezzanine",
                        quote,
                        optionsTable
                );
            }

            // add stairs to the quote options list
            if (quote.getStairsNoTurns() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getStairsNoTurns()),
                        "Stairs (No Turns)",
                        quote,
                        optionsTable
                );

            // add stairs to the quote options list
            if (quote.getStairsOneTurn() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getStairsOneTurn()),
                        "Stairs (One Turn)",
                        quote,
                        optionsTable
                );

            // add stairs to the quote options list
            if (quote.getStairsTwoTurns() > 0)
                createQuoteOptionRow(
                        String.valueOf(quote.getStairsTwoTurns()),
                        "Stairs (Two Turns)",
                        quote,
                        optionsTable
                );

            // add customs to the quote options list
            for (int i = 0; i < customsList.length(); i++) {
                // get each
                JSONObject itemList = (JSONObject)customsList.get(i);

                createQuoteOptionRow(
                        "",
                        itemList.getString("details"),
                        quote,
                        optionsTable
                );
            }

        } catch (JSONException e) {
            System.out.println("asdf JSON no go go: " + e);
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        defaultFormat = NumberFormat.getCurrencyInstance(getCurrentLocale(getActivity().getApplicationContext()));

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_quote_view, container, false);

        String inputsTag = getTag();

        ((QuoteDetailsActivity)getActivity()).setQuoteInputs(inputsTag);

   //     Intent intent = getActivity().getIntent();
   //     quote = (Quote) intent.getSerializableExtra("quote");
        String customerCompanyDescription = "";

        TextView salesmanName = (TextView)v.findViewById(R.id.salesman_name);
        TextView salesmanPhone = (TextView)v.findViewById(R.id.salesman_phone);
        TextView salesmanEmail = (TextView)v.findViewById(R.id.salesman_email);
        customerName = (TextView)v.findViewById(R.id.customer_name);
        TextView customerPhone = (TextView)v.findViewById(R.id.customer_phone);
        TextView customerEmail = (TextView)v.findViewById(R.id.customer_email);
        TextView customerCity = (TextView)v.findViewById(R.id.customer_city);
        TextView customerProvince = (TextView)v.findViewById(R.id.customer_province);
        TextView customerPostalCode = (TextView)v.findViewById(R.id.customer_postal_Code);
        TextView customerExtraReference = (TextView)v.findViewById(R.id.customer_extra_reference);
        quoteNumber = (TextView)v.findViewById(R.id.quote_number);
        quoteDate = (TextView)v.findViewById(R.id.quote_date);
        quoteExpiry = (TextView)v.findViewById(R.id.quote_expiry);
        quotePrice = (TextView)v.findViewById(R.id.quote_price);
        buildingDetails = (TextView)v.findViewById(R.id.building_details);
        buildingClassification = (TextView)v.findViewById(R.id.quote_classification);
        trussDescription = (TextView)v.findViewById(R.id.quote_truss_description);
        strappingDescription = (TextView)v.findViewById(R.id.quote_strapping_description);
        metalDescription = (TextView)v.findViewById(R.id.quote_metal_description);
        ridgeDescription = (TextView)v.findViewById(R.id.quote_ridge_description);
        stormBracketDescription = (TextView)v.findViewById(R.id.quote_storm_bracket_description);
        blueprintsDescription = (TextView)v.findViewById(R.id.quote_blueprints_description);
        wallDescription = (TextView)v.findViewById(R.id.wall_description);
        ceilingInsulationDescription = (TextView)v.findViewById(R.id.ceiling_insulation_description);
        insulationSectionHeader = (TextView)v.findViewById(R.id.quote_insulation_section_header);
        quotePrice2 = (TextView)v.findViewById(R.id.quote_price_subsection);
        upgradePrice3PlyPerma = (TextView)v.findViewById(R.id.upgrade_price_3PlyPerma);
        upgradePrice4PlyPerma = (TextView)v.findViewById(R.id.upgrade_price_4PlyPerma);
        upgradePrice8400Perma = (TextView)v.findViewById(R.id.upgrade_price_8400Perma);

        quoteInsulationSection = (LinearLayout)v.findViewById(R.id.quote_insulation_section);
        quoteInsulationSubsection = (LinearLayout)v.findViewById(R.id.quote_insulation_subsection);
        warrantySection = (LinearLayout)v.findViewById(R.id.quote_warranty_subsection);

        optionsTable = v.findViewById(R.id.options_table);
        upgradesTable = v.findViewById(R.id.upgrades_table);

        upgradeRow3PlyPerma = (TableRow)v.findViewById(R.id.upgrade_row_3PlyPerma);
        upgradeRow4PlyPerma = (TableRow)v.findViewById(R.id.upgrade_row_4PlyPerma);
        upgradeRow8400Perma = (TableRow)v.findViewById(R.id.upgrade_row_8400Perma);

        salesmanName.setText(quote.getAssignedName());
   //     salesmanPhone.setText(user.getPhone());
  //      salesmanEmail.setText(user.getEmail());
        if (!quote.getCustomerCompany().equals(""))
            customerCompanyDescription = quote.getCustomerCompany() + " care of ";

        customerName.setText(quote.getCustomerFirstName() + " " + quote.getCustomerLastName());
        customerPhone.setText(PhoneNumberUtils.formatNumber(quote.getCustomerPhone()));
        customerEmail.setText(quote.getCustomerEmail());
        customerCity.setText(quote.getCustomerCity());
//       customerProvince.setText(quote.getCustomerProvinceId());
        customerPostalCode.setText(quote.getCustomerPostalCode());
        customerExtraReference.setText(quote.getCustomerExtraReference());

//       LoadQuoteValuesAsynchronously quoteValueLoader = new LoadQuoteValuesAsynchronously(this, getContext().getContentResolver(), quote);
  //      quoteValueLoader.execute();
//       loadQuoteValues();

        return v;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.menu_chat_fragment, menu);
            super.onCreateOptionsMenu(menu, inflater);
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getCurrentLocale(Context c) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return c.getResources().getConfiguration().getLocales().get(0);
        } else {
            //noinspection deprecation
            return c.getResources().getConfiguration().locale;
        }
    }

    public String formatDate(String date, int addDays)
    {
        String dateString = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", getCurrentLocale(getActivity().getApplicationContext()));
        SimpleDateFormat outputFormat = new SimpleDateFormat("MMM d, yyyy", getCurrentLocale(getActivity().getApplicationContext()));
        try {
            Date newDate = format.parse(date);
            if (addDays > 0)
            {
                Calendar c = Calendar.getInstance();
                c.setTime(newDate);
                c.add(Calendar.DATE, addDays);
                newDate = c.getTime();
            }
            dateString = outputFormat.format(newDate);
        } catch (ParseException e) {
            System.out.println("asdf error: " + e);
            e.printStackTrace();
        }

        return dateString;
    }

    public void createQuoteOptionRow(String itemQuantity, String itemDescription, Quote quote, TableLayout optionsTable)
    {
        TableRow tr = new TableRow(getActivity());
        TextView itemQuantityTextView = new TextView(getActivity());
        TextView itemDescriptionTextView = new TextView(getActivity());
        TableRow.LayoutParams tableLayoutParamsQuantity = new TableRow.LayoutParams(
                0,
                TableRow.LayoutParams.WRAP_CONTENT);
        tableLayoutParamsQuantity.weight = (float) 0.23;
        TableRow.LayoutParams tableLayoutParamsDescription = new TableRow.LayoutParams(
                0,
                TableRow.LayoutParams.WRAP_CONTENT);
        tableLayoutParamsDescription.weight = (float) 0.77;
        TableLayout.LayoutParams tableLayoutParamsRow = new TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);

        // set the text for each textview
        itemQuantityTextView.setText(itemQuantity);
        itemDescriptionTextView.setText(itemDescription);

        // set the background in order to get a table border
        itemQuantityTextView.setBackgroundResource(R.drawable.quote_options_border);
        itemDescriptionTextView.setBackgroundResource(R.drawable.quote_options_border);

        // this gravity and one above are needed to center the text
        itemQuantityTextView.setPadding(10, 10, 10, 10);
        itemQuantityTextView.setGravity(Gravity.CENTER);
        itemDescriptionTextView.setPadding(10, 10, 10, 10);

        // apply the layout parameters to the textviews
        itemQuantityTextView.setLayoutParams(tableLayoutParamsQuantity);
        itemDescriptionTextView.setLayoutParams(tableLayoutParamsDescription);
        tr.setLayoutParams(tableLayoutParamsRow);

        // add the views to the row and the row to the table
        tr.addView(itemQuantityTextView);
        tr.addView(itemDescriptionTextView);
        optionsTable.addView(tr);
    }

    public String getNameFromMaterialId(int itemId)
    {
        String returnValue = "";

        final ContentResolver contentResolver = getContext().getContentResolver();
        Uri uri = MaterialsContract.Entry.CONTENT_URI; // Get all entries
        Cursor materialsCursor = contentResolver.query(uri, new String[] {"item_name"}, " entry_id = ?", new String[] { String.valueOf(itemId) }, null);
        assert materialsCursor != null;
        if (materialsCursor.getCount() > 0) {
            materialsCursor.moveToFirst();
            returnValue = materialsCursor.getString(0).replaceAll("&#39;", "'").replaceAll("&#039;", "'");
        }

        return returnValue;
    }

    private int getItemQuantity(int itemId, int quoteId)
    {
        int returnValue = 0;

        final ContentResolver contentResolver = getContext().getContentResolver();
        Uri uri = QuoteMaterialsContract.Entry.CONTENT_URI; // Get all entries
        Cursor materialsCursor = contentResolver.query(uri, new String[] {"quantity"}, " product_id = ? and quote_id = ?", new String[] { String.valueOf(itemId), String.valueOf(quoteId) }, null);
        assert materialsCursor != null;
        if (materialsCursor.getCount() > 0) {
            materialsCursor.moveToFirst();
            String quantitiesString = materialsCursor.getString(0);

            // remove the extra array characters
            quantitiesString = quantitiesString
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");
            // create an array list from the comman delimited string of quantities
            List<String> quantitiesList = new ArrayList<String>(Arrays.asList(quantitiesString.split(",")));
            // loop through array and add up all the quantities
            for (int i = 0; i < quantitiesList.size(); i++)
                returnValue =+ Integer.parseInt(quantitiesList.get(i));
        }

        return returnValue;
    }

}


class LoadQuoteValuesAsynchronously extends AsyncTask<String, Void, String> {
    ContentResolver contentResolver;
    Quote quote;
    private QuoteViewFragment quoteViewFragment;
    Long startTime;

    public LoadQuoteValuesAsynchronously(QuoteViewFragment quoteViewFragment, ContentResolver contentResolver, Quote quote, Long startTime) {
        this.quoteViewFragment = quoteViewFragment;
        this.contentResolver = contentResolver;
        this.quote = quote;
        this.startTime = startTime;
  //      System.out.println("asdf six: " + (System.currentTimeMillis() - startTime));
    }

    protected String doInBackground(String... params) {
        int count = 0;
   //     System.out.println("asdf seven: " + (System.currentTimeMillis() - startTime));
        // make a manual database call to get the name of the selected post type
        Uri uri = QuoteMaterialsContract.Entry.CONTENT_URI; // Get all entries
   //     System.out.println("asdf quote to retrieve materials is " + quote.getQuoteId());
        Cursor quoteMaterialsCursor = contentResolver.query(uri, QuoteMaterialsContract.Entry.PROJECTION, " quote_id = ?", new String[] { String.valueOf(quote.getQuoteId()) }, " product_id asc");
        assert quoteMaterialsCursor != null;
     //   System.out.println("asdf materials cursor size: " + quoteMaterialsCursor.getCount());
        Map<String, String> materialsHashmap = new HashMap<String, String>();
  //      System.out.println("asdf eight: " + (System.currentTimeMillis() - startTime));
        while (quoteMaterialsCursor.moveToNext()) {
  //          if (count % 50 == 0)
  //              System.out.println("asdf nine: " + (System.currentTimeMillis() - startTime));
            Map<String, String> columns = new HashMap<String, String>();

            // create a hashmap from each row
            for (int i = 0; i < quoteMaterialsCursor.getColumnCount(); i++)
                columns.put(quoteMaterialsCursor.getColumnName(i), quoteMaterialsCursor.getString(i));

//            if (count % 50 == 0)
//                System.out.println("asdf ten: " + (System.currentTimeMillis() - startTime));
            JSONObject jsonColumns = new JSONObject(columns);

            try {
                materialsHashmap.put(jsonColumns.getString("product_id"), jsonColumns.toString());
            } catch (JSONException e) {
                System.out.println("asdf error: " + e);
                e.printStackTrace();
            }

            count++;

        }
//       System.out.println("asdf eleven: " + (System.currentTimeMillis() - startTime));

        quoteMaterialsCursor.close();

        JSONObject jsonMaterials = new JSONObject(materialsHashmap);
  //      System.out.println("asdf set materials to " + jsonMaterials.toString());
        quote.setMaterials(jsonMaterials.toString());
//       System.out.println("asdf twelve: " + (System.currentTimeMillis() - startTime));

        return "";
    }

    @Override
    protected void onPostExecute(String s){
        // load all values into quote
//       System.out.println("asdf 98: " + (System.currentTimeMillis() - startTime));
        quoteViewFragment.loadQuoteValues();
//       System.out.println("asdf 99: " + (System.currentTimeMillis() - startTime));
    }
}
 
Upvote 0
Here is the quote model that holds everything related to the quote you're working on.

Java:
package com.example.android.basicsyncadapter.model;

import android.app.Application;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import com.example.android.basicsyncadapter.provider.MaterialsContract;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Quote extends Application implements Serializable {

    private ContentResolver contentResolver;
    private int id;
    private String number;
    private int customerId;
    private int buildingTypeId;
    private int userId;
    private int assignedId;
    private String estimatedDeliveryDate;
    private int showTaxes;
    private double price;
    private double deposit1;
    private double deposit2;
    private double deposit3;
    private double deposit4;
    private String gps;
    private String contractDate;
    private String contractDeliveryDate;
    private String reminderDate;
    private String quotedDate;
    private String confirmedDate;
    private String orderedDate;
    private String finishedDate;
    private String upgradeOptionsPrices;
    private String attachmentFolderId;
    private int attachmentFolderIncrementalValue;
    private int parentQuoteId;
    private int deleted;
    private String created;

    private String customerCompany;
    private String customerFirstName;
    private String customerLastName;
    private String customerAddress1;
    private String customerAddress2;
    private String customerPhone;
    private String customerFax;
    private String customerEmail;
    private String customerCity;
    private int customerProvinceId;
    private String customerPostalCode;
    private int customerReferrerId;
    private String customerReferrerOther;
    private String customerGps;
    private int customerParentId;
    private String customerCreated;
    private String extraReference;

    private int inputsId;
    private String inputs;
    private String materials;

    private boolean isMaterialOnly;
    private boolean isWarranty5;
    private boolean isBlueprints;
    //    private
    private String buildingType;
    private int occupancyId;
    private String occupancy;
    private int snowLoadLevel;
    private boolean isOilAndGas;
    private int width;
    private int length;
    private int height;
    private double trussPrice;
    private double pitch;
    private int heelHeight;
    private int driftLoadRaftersQuantity;
    private boolean isDoublePlyRafters;
    private boolean isPostDiscs;
    private int wallTypeId;
    private String wallType;
    private int evePostSpacing;
    private int gablePostSpacing;

    private int gableVents;
    private int eveSoffitLength;
    private boolean stormBrackets;
    private int stormBracketQuantity;
    private int smokeStops;
    private int gableSoffitLength;
    private boolean xTensionStraps;
    private int xTensionStrapQuantity;
    private int gableStops;
    private int tightSiteEve;
    private String ridge;
    private int fireStops;
    private int tightSiteGable;
    private boolean insulated;
    private int insulationWidth;
    private int insulationLength;
    private boolean ceilingOnly;
    private int ceilingWidth;
    private int ceilingLength;
    private int insulationDensity;
    private int atticHatches;
    private int additionalAtticHatches;
    private boolean codeBoard;
    private int stairsNoTurns;
    private int stairsOneTurn;
    private int stairsTwoTurns;
    private int colourAccent;
    private int colourWallMetal;
    private int colourGableMetal;
    private int colourRoofMetal;
    private int colourTrimMetal;
    private int colourFoldingDoor;
    private int colourSlidingDoor;
    private int colourSoffit;
    private int colourWainscoting;
    private int eveAccentQuantity;
    private int gableAccentQuantity;

    private boolean is3PlyPermaPostUpgrade;
    private boolean is4PlyPermaPostUpgrade;
    private boolean is8400PermaPostUpgrade;
    private int eveSoffitUpgradeLength;
    private int gableSoffitUpgradeLength;
    private int stormBracketUpgradeQuantity;
    private int xTensionStrapsUpgradeQuantity;
    private boolean isShearWallUpgrade;
    private boolean isKickWallInsulationUpgrade;
    private boolean isInsulationR40Upgrade;
    private boolean isInsulationR50Upgrade;
    private boolean isInsulationR60Upgrade;
    private boolean isCeilingOnlyUpgrade;

    private String promotionalCode;
    private double sellingPrice;
    private int webLaterals;
    private int bottomCordSpacing;
    private boolean isTestQuote;
    private boolean isTradeShowQuote;

    private String assignedName;

    private String overheadDoorsJson = "[]";
    private String slidingDoorsJson = "[]";
    private String foldingDoorsJson = "[]";
    private String manDoorsJson = "[]";
    private String windowsJson = "[]";
    private String customWindowsJson = "[]";
    private String wallLightJson = "[]";
    private String kickWallJson = "[]";
    private String partitionWallJson = "[]";
    private String mezzanineJson = "[]";
    private String leanToJson = "[]";
    private String customsJson = "[]";

    private String inputExtraReference = "customer-extra-reference";
    private String inputMaterialOnly = "material-only";
    private String inputWarranty5 = "warranty5";
    private String inputBlueprints = "blueprints";
    private String inputOccupancy = "occupancy";
    private String inputSnowLoadLevel = "snow-load-level";
    private String inputBuildingType = "building-type";
    private String inputOilAndGas = "is-oil-and-gas";
    private String inputBuildingWidth = "building-width";
    private String inputBuildingLength = "building-length";
    private String inputBuildingHeight = "building-height";
    private String inputTrussPrice = "building-truss-price";
    private String inputPitch = "building-pitch";
    private String inputHeelHeight = "building-heel-height";
    private String inputDriftLoadRafters = "drift-load-rafters";
    private String inputDoublePlyRafters = "double-ply-rafters";
    private String inputPostDiscs = "post-discs";
    private String inputPostType = "post-type";
    private String inputEvePostSpacing = "eve-post-spacing";
    private String inputGablePostSpacing = "gable-post-spacing";
    private String inputGableVents = "gable-vents";
    private String inputSmokeStop = "smoke-stop";
    private String inputGableStop = "gable-stop";
    private String inputFireStop = "fire-stop";
    private String inputEveSoffitLength = "eve-soffit-length";
    private String inputGableSoffitLength = "gable-soffit-length";
    private String inputTightSiteEve = "tight-site-eve";
    private String inputTightSiteGable = "tight-site-gable";
    private String inputStormBracket = "storm-bracket";
    private String inputStormBracketQuantity = "storm-bracket-quantity";
    private String inputXTension = "x-tension";
    private String inputXTensionQuantity = "x-tension-quantity";
    private String inputRidge = "ridge";
    private String inputInsulated = "insulated";
    private String inputInsulationWidth = "insulation-width";
    private String inputInsulationLength = "insulation-length";
    private String inputCeiling = "ceiling";
    private String inputCeilingWidth = "ceiling-width";
    private String inputCeilingLength = "ceiling-length";
    private String inputInsulationDensity = "insulation-density";
    private String inputAtticHatchQuantity = "attic-hatch-quantity";
    private String inputAdditionalAtticHatchQuantity = "additional-attic-hatch-quantity";
    private String inputCodeBoard = "code-board";
    private String inputStairsZeroQuantity = "stairs-zero-quantity";
    private String inputStairsOneQuantity = "stairs-one-quantity";
    private String inputStairsTwoQuantity = "stairs-two-quantity";

    private String inputColourAccent = "colour-accent";
    private String inputColourWallMetal = "colour-wall-metal";
    private String inputColourGableMetal = "colour-gable-metal";
    private String inputColourRoofMetal = "colour-roof-metal";
    private String inputColourTrim = "colour-trim";
    private String inputColourFoldingDoor = "colour-bi-fold-door";
    private String inputColourSlidingDoor = "colour-sliding-door";
    private String inputColourSoffit = "colour-soffit-colour";
    private String inputColourWainscoting = "colour-wainscoting";

    private String inputEveAccentQuantity = "eve-accent-quantity";
    private String inputGableAccentQuantity = "gable-accent-quantity";

    private String input3PlyPermaColumnUpgrade = "show-perma-cost-1";
    private String input4PlyPermaColumnUpgrade = "show-perma-cost-2";
    private String input8400PermaColumnUpgrade = "show-perma-cost-3";
    private String inputEveSoffitUpgrade = "eve-soffit-upgrade-length";
    private String inputGableSoffitUpgrade = "gable-soffit-upgrade-length";
    private String inputStormBracketUpgrade = "storm-bracket-upgrade-option";
    private String inputXTensionUpgrade = "x-tension-upgrade-option";
    private String inputShearWallUpgrade = "shear-wall-upgrade-option";
    private String inputKickWallInsulationUpgrade = "kick-wall-insulation-upgrade-option";
    private String inputInsulationR40Upgrade = "show-insulation-cost";
    private String inputInsulationR50Upgrade = "show-insulation-cost-r50";
    private String inputInsulationR60Upgrade = "show-insulation-cost-r60";
    private String inputCeilingOnlyUpgrade = "show-ceiling-cost";

    private String inputPromotionalCode = "promotion";
    private String inputSellingPrice = "selling-price";
    private String inputRemindMe = "reminder-date";
    private String inputWebLaterals = "web-laterals";
    private String inputBottomCordSpacing = "bottom-cord";
    private String inputTestQuote = "test-quote";
    private String inputTradeShowQuote = "trade-show-quote";

    private String inputOverheads = "overheads";
    private String inputSliding = "sliding";
    private String inputFolding = "folding";
    private String inputManDoors = "man-doors";
    private String inputWindows = "windows";
    private String inputCustomWindows = "custom-windows";
    private String inputWallLight = "wall-lights";
    private String inputKickWall = "kick-wall";
    private String inputPartitionWall = "partition-wall";
    private String inputMezzanines = "mezzanines";
    private String inputLeanTos = "lean-tos";
    private String inputCustoms = "customs";
    private static Application instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public final int FIXED_WINDOW_DUAL_PANE_3X5 = 1;
    public final int QUALITY_MANAGEMENT = 2;
    public final int CUSTOM_MATERIALS = 3;
    public final int CUSTOM_LABOUR = 4;
    public final int PEAK_SIGN = 5;
    public final int EXTERIOR_HEIGHT_LABOUR_PREMIUM = 6;
    public final int INTERIOR_HEIGHT_LABOUR_PREMIUM = 7;
    public final int PLYWOOD_QUARTER_INCH = 8;
    public final int SHEAR_WALL_LABOUR = 9;
    public final int EXTERIOR_LABOUR_8600_PLUS = 10;
    public final int INTERIOR_LABOUR_8600_PLUS = 11;
    public final int X_TENSION_STRAPS = 12;
    public final int POLY_CARBONATE_PANEL = 13;
    public final int ACQ_2X8X12 = 14;
    public final int ACQ_2X8X16 = 15;
    public final int SPF_2X6X12 = 16;
    public final int SPF_2X6X16 = 17;
    public final int SPF_2X8X12 = 18;
    public final int SPF_2X8X16 = 19;
    public final int SPF_2X4X12 = 20;
    public final int SPF_2X4X16 = 21;
    public final int STORM_BRACKET = 22;
    public final int SPF_2X10X16 = 23;
    public final int FILLER_BOARD_2X6X16_ACQ = 24;
    public final int FILLER_BOARD_2X6X12_ACQ = 25;
    public final int SMOKE_DAMPERS = 284;

    public int getQuoteId() {
        return id;
    }

    public void setQuoteId(int id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public int getBuildingTypeId() {
        return buildingTypeId;
    }

    public void setBuildingTypeId(int buildingTypeId) {
        this.buildingTypeId = buildingTypeId;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getAssignedId() {
        return assignedId;
    }

    public void setAssignedId(int assignedId) {
        this.assignedId = assignedId;
    }

    public String getEstimatedDeliveryDate() {
        return estimatedDeliveryDate;
    }

    public void setEstimatedDeliveryDate(String estimatedDeliveryDate) {
        this.estimatedDeliveryDate = estimatedDeliveryDate;
    }

    public int getShowTaxes() {
        return showTaxes;
    }

    public void setShowTaxes(int showTaxes) {
        this.showTaxes = showTaxes;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public double getDeposit1() {
        return deposit1;
    }

    public void setDeposit1(double deposit1) {
        this.deposit1 = deposit1;
    }

    public double getDeposit2() {
        return deposit2;
    }

    public void setDeposit2(double deposit2) {
        this.deposit2 = deposit2;
    }

    public double getDeposit3() {
        return deposit3;
    }

    public void setDeposit3(double deposit3) {
        this.deposit3 = deposit3;
    }

    public double getDeposit4() {
        return deposit4;
    }

    public void setDeposit4(double deposit4) {
        this.deposit4 = deposit4;
    }

    public String getGps() {
        return gps;
    }

    public void setGps(String gps) {
        this.gps = gps;
    }

    public String getContractDate() {
        return contractDate;
    }

    public void setContractDate(String contractDate) {
        this.contractDate = contractDate;
    }

    public String getContractDeliveryDate() {
        return contractDeliveryDate;
    }

    public void setContractDeliveryDate(String contractDeliveryDate) {
        this.contractDeliveryDate = contractDeliveryDate;
    }

    public String getReminderDate() {
        return reminderDate;
    }

    public void setReminderDate(String reminderDate) {
        this.reminderDate = reminderDate;
    }

    public String getQuotedDate() {
        return quotedDate;
    }

    public void setQuotedDate(String quotedDate) {
        this.quotedDate = quotedDate;
    }

    public String getConfirmedDate() {
        return confirmedDate;
    }

    public void setConfirmedDate(String confirmedDate) {
        this.confirmedDate = confirmedDate;
    }

    public String getOrderedDate() {
        return orderedDate;
    }

    public void setOrderedDate(String orderedDate) {
        this.orderedDate = orderedDate;
    }

    public String getFinishedDate() {
        return finishedDate;
    }

    public void setFinishedDate(String finishedDate) {
        this.finishedDate = finishedDate;
    }

    public String getUpgradeOptionsPrices() {
        return upgradeOptionsPrices;
    }

    public void setUpgradeOptionsPrices(String upgradeOptionsPrices) {
        this.upgradeOptionsPrices = upgradeOptionsPrices;
    }

    public String getAttachmentFolderId() {
        return attachmentFolderId;
    }

    public void setAttachmentFolderId(String attachmentFolderId) {
        this.attachmentFolderId = attachmentFolderId;
    }

    public int getAttachmentFolderIncrementalValue() {
        return attachmentFolderIncrementalValue;
    }

    public void setAttachmentFolderIncrementalValue(int attachmentFolderIncrementalValue) {
        this.attachmentFolderIncrementalValue = attachmentFolderIncrementalValue;
    }

    public int getParentQuoteId() {
        return parentQuoteId;
    }

    public void setParentQuoteId(int parentQuoteId) {
        this.parentQuoteId = parentQuoteId;
    }

    public int getDeleted() {
        return deleted;
    }

    public void setDeleted(int deleted) {
        this.deleted = deleted;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }

    public String getCustomerCompany() {
        return customerCompany;
    }

    public void setCustomerCompany(String customerCompany) {
        this.customerCompany = customerCompany;
    }

    public String getCustomerFirstName() {
        return customerFirstName;
    }

    public void setCustomerFirstName(String customerFirstName) {
        this.customerFirstName = customerFirstName;
    }

    public String getCustomerLastName() {
        return customerLastName;
    }

    public void setCustomerLastName(String customerLastName) {
        this.customerLastName = customerLastName;
    }

    public String getCustomerAddress1() {
        return customerAddress1;
    }

    public void setCustomerAddress1(String customerAddress1) {
        this.customerAddress1 = customerAddress1;
    }

    public String getCustomerAddress2() {
        return customerAddress2;
    }

    public void setCustomerAddress2(String customerAddress2) {
        this.customerAddress2 = customerAddress2;
    }

    public String getCustomerPhone() {
        return customerPhone;
    }

    public void setCustomerPhone(String customerPhone) {
        this.customerPhone = customerPhone;
    }

    public String getCustomerFax() {
        return customerFax;
    }

    public void setCustomerFax(String customerFax) {
        this.customerFax = customerFax;
    }

    public String getCustomerEmail() {
        return customerEmail;
    }

    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    public String getCustomerCity() {
        return customerCity;
    }

    public void setCustomerCity(String customerCity) {
        this.customerCity = customerCity;
    }

    public int getCustomerProvinceId() {
        return customerProvinceId;
    }

    public void setCustomerProvinceId(int customerProvinceId) {
        this.customerProvinceId = customerProvinceId;
    }

    public String getCustomerPostalCode() {
        return customerPostalCode;
    }

    public void setCustomerPostalCode(String customerPostalCode) {
        this.customerPostalCode = customerPostalCode;
    }

    public int getCustomerReferrerId() {
        return customerReferrerId;
    }

    public void setCustomerReferrerId(int customerReferrerId) {
        this.customerReferrerId = customerReferrerId;
    }

    public String getCustomerReferrerOther() {
        return customerReferrerOther;
    }

    public void setCustomerReferrerOther(String customerReferrerOther) {
        this.customerReferrerOther = customerReferrerOther;
    }

    public String getCustomerExtraReference() {
        return extraReference;
    }

    public void setCustomerExtraReference(String extraReference) {
        this.extraReference = extraReference;
    }

    public String getCustomerGps() {
        return customerGps;
    }

    public void setCustomerGps(String customerGps) {
        this.customerGps = customerGps;
    }

    public int getCustomerParentId() {
        return customerParentId;
    }

    public void setCustomerParentId(int customerParentId) {
        this.customerParentId = customerParentId;
    }

    public String getCustomerCreated() {
        return customerCreated;
    }

    public void setCustomerCreated(String customerCreated) {
        this.customerCreated = customerCreated;
    }

    public int getInputsId() {
        return inputsId;
    }

    public void setInputsId(int customerCity) {
        this.inputsId = inputsId;
    }

    public String getAssignedName() {
        return assignedName;
    }

    public void setAssignedName(String assignedName) {
        this.assignedName = assignedName;
    }

    public String getInputs() {
        return inputs;
    }

    public void setInputs(String inputs) {
        this.inputs = inputs;

        JSONObject json;

        try {
            // parse JSON string of inputs to get the data we want
            json = new JSONObject(inputs);

   //         System.out.println("asdf json stuff: " + json.getString(inputOverheads));

            String sellingPrice = json.getString("selling-price");
            if (!sellingPrice.equals(""))
                setSellingPrice(Double.valueOf(sellingPrice));
            setBuildingWidth(json.getInt(inputBuildingWidth));
            setBuildingLength(json.getInt(inputBuildingLength));
            setBuildingHeight(json.getInt(inputBuildingHeight));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputMaterialOnly))
                setMaterialOnly(json.getString(inputMaterialOnly).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputWarranty5 + '"'))
                setWarranty5(json.getString(inputWarranty5).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputBlueprints + '"'))
                setBlueprints(json.getString(inputBlueprints).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputOilAndGas))
                setOilAndGas(json.getString(inputOilAndGas).equals("true"));
            setTrussPrice(json.getDouble(inputTrussPrice));
            setPitch(json.getDouble(inputPitch));
            setHeelHeight(json.getInt(inputHeelHeight));
            // integer parsing fails on empty strings
            if (json.getString(inputDriftLoadRafters).equals(""))
                setDriftLoadRafters(0);
            else
                setDriftLoadRafters(Integer.parseInt(json.getString(inputDriftLoadRafters)));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputDoublePlyRafters))
                setDoublePlyRafters(json.getString(inputDoublePlyRafters).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputPostDiscs))
                setPostDiscs(json.getString(inputPostDiscs).equals("true"));
            setWallTypeId(json.getInt(inputPostType));
            setWallType(json.getString("post-type"));
            setEvePostSpacing(json.getInt(inputEvePostSpacing));
            setGablePostSpacing(json.getInt(inputGablePostSpacing));
            // integer parsing fails on empty strings
            if (json.getString(inputGableVents).equals(""))
                setGableVents(0);
            else
                setGableVents(json.getInt(inputGableVents));
            // integer parsing fails on empty strings
            if (json.getString(inputEveSoffitLength).equals(""))
                setEveSoffitLength(0);
            else
                setEveSoffitLength(json.getInt(inputEveSoffitLength));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputStormBracket + '"'))
                setStormBrackets(json.getString(inputStormBracket).equals("true"));
            // integer parsing fails on empty strings
            if (json.getString(inputStormBracketQuantity).equals(""))
                setStormBracketQuantity(0);
            else
                setStormBracketQuantity(json.getInt(inputStormBracketQuantity));
            // integer parsing fails on empty strings
            if (json.getString(inputSmokeStop).equals(""))
                setSmokeStops(0);
            else
                setSmokeStops(json.getInt(inputSmokeStop));
            // integer parsing fails on empty strings
            if (json.getString(inputGableSoffitLength).equals(""))
                setGableSoffitLength(0);
            else
                setGableSoffitLength(json.getInt(inputGableSoffitLength));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputXTension + '"'))
                setXTensionStraps(json.getString(inputXTension).equals("true"));
            setXTensionStrapQuantity(json.getInt(inputXTensionQuantity));
            // integer parsing fails on empty strings
            if (json.getString(inputGableStop).equals(""))
                setGableStops(0);
            else
                setGableStops(json.getInt(inputGableStop));
            // integer parsing fails on empty strings
            if (json.getString(inputTightSiteEve).equals(""))
                setTightSiteEve(0);
            else
                setTightSiteEve(json.getInt(inputTightSiteEve));
            // integer parsing fails on empty strings
            if (json.getString(inputTightSiteGable).equals(""))
                setTightSiteGable(0);
            else
                setTightSiteGable(json.getInt(inputTightSiteGable));
            setRidge(json.getString(inputRidge));
            // integer parsing fails on empty strings
            if (json.getString(inputFireStop).equals(""))
                setFireStops(0);
            else
                setFireStops(json.getInt(inputFireStop));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputInsulated + '"'))
                setInsulated(json.getString(inputInsulated).equals("true"));
            // integer parsing fails on empty strings
            if (json.getString(inputInsulationWidth).equals(""))
                setInsulationWidth(0);
            else
                setInsulationWidth(json.getInt(inputInsulationWidth));
            // integer parsing fails on empty strings
            if (json.getString(inputInsulationLength).equals(""))
                setInsulationLength(0);
            else
                setInsulationLength(json.getInt(inputInsulationLength));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputCeiling + '"'))
                setCeilingOnly(json.getString(inputCeiling).equals("true"));
            // integer parsing fails on empty strings
            if (json.getString(inputCeilingWidth).equals(""))
                setCeilingWidth(0);
            else
                setCeilingWidth(json.getInt(inputCeilingWidth));
            // integer parsing fails on empty strings
            if (json.getString(inputCeilingLength).equals(""))
                setCeilingLength(0);
            else
                setCeilingLength(json.getInt(inputCeilingLength));
            setInsulationDensity(json.getInt(inputInsulationDensity));
            setAtticHatches(json.getInt(inputAtticHatchQuantity));
            // integer parsing fails on empty strings
            if (json.getString(inputAdditionalAtticHatchQuantity).equals(""))
                setAdditionalAtticHatches(0);
            else
                setAdditionalAtticHatches(json.getInt(inputAdditionalAtticHatchQuantity));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputCodeBoard))
                setCodeBoard(json.getString(inputCodeBoard).equals("true"));
            setAccentColour(json.getInt(inputColourAccent));
            setWallMetalColour(json.getInt(inputColourWallMetal));
            setGableMetalColour(json.getInt(inputColourGableMetal));
            setRoofColour(json.getInt(inputColourRoofMetal));
            setTrimColour(json.getInt(inputColourTrim));
            setFoldingDoorColour(json.getInt(inputColourFoldingDoor));
            setSlidingDoorColour(json.getInt(inputColourSlidingDoor));
            setSoffitColour(json.getInt(inputColourSlidingDoor));
            setWainscotingColour(json.getInt(inputColourWainscoting));
            // integer parsing fails on empty strings
            if (json.getString(inputEveAccentQuantity).equals(""))
                setEveAccentQuantity(0);
            else
                setEveAccentQuantity(json.getInt(inputEveAccentQuantity));
            // integer parsing fails on empty strings
            if (json.getString(inputGableAccentQuantity).equals(""))
                setGableAccentQuantity(0);
            else
                setGableAccentQuantity(json.getInt(inputGableAccentQuantity));
            setOccupancyId(json.getInt(inputOccupancy));
            setCustomerExtraReference(json.getString(inputExtraReference));
            setPromotionalCode(json.getString(inputPromotionalCode));
            setReminderDate(json.getString(inputRemindMe));
            setWebLaterals(json.getInt(inputWebLaterals));
            setBottomCordSpacing(json.getInt(inputBottomCordSpacing));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputTestQuote + '"'))
                setTestQuote(json.getString(inputTestQuote).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains('"' + inputTradeShowQuote + '"'))
                setTradeShowQuote(json.getString(inputTradeShowQuote).equals("true"));

            if (!json.getString(inputOverheads).equals(""))
                setOverheadDoors((new JSONArray(json.getString(inputOverheads)).toString()));

            if (!json.getString(inputSliding).equals(""))
                setSlidingDoors((new JSONArray(json.getString(inputSliding)).toString()));

            if (!json.getString(inputFolding).equals(""))
                setFoldingDoors((new JSONArray(json.getString(inputFolding)).toString()));

            if (!json.getString(inputManDoors).equals(""))
                setManDoors((new JSONArray(json.getString(inputManDoors)).toString()));

            if (!json.getString(inputWindows).equals(""))
                setWindows((new JSONArray(json.getString(inputWindows)).toString()));

            if (!json.getString(inputCustomWindows).equals(""))
                setCustomWindows((new JSONArray(json.getString(inputCustomWindows)).toString()));

            if (!json.getString(inputWallLight).equals(""))
                setWallLights((new JSONArray(json.getString(inputWallLight)).toString()));

            if (!json.getString(inputKickWall).equals(""))
                setKickWall((new JSONArray(json.getString(inputKickWall)).toString()));

            if (!json.getString(inputPartitionWall).equals(""))
                setPartitionWalls((new JSONArray(json.getString(inputPartitionWall)).toString()));

            if (!json.getString(inputMezzanines).equals(""))
                setMezzanines((new JSONArray(json.getString(inputMezzanines)).toString()));

            if (!json.getString(inputLeanTos).equals(""))
                setLeanTos((new JSONArray(json.getString(inputLeanTos)).toString()));

            if (!json.getString(inputCustoms).equals(""))
                setCustoms((new JSONArray(json.getString(inputCustoms)).toString()));

            if (!json.getString(inputStairsZeroQuantity).equals(""))
                setStairsNoTurns(Integer.parseInt(json.getString(inputStairsZeroQuantity)));
            if (!json.getString(inputStairsOneQuantity).equals(""))
                setStairsOneTurn(Integer.parseInt(json.getString(inputStairsOneQuantity)));
            if (!json.getString(inputStairsTwoQuantity).equals(""))
                setStairsTwoTurns(Integer.parseInt(json.getString(inputStairsTwoQuantity)));

            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(input3PlyPermaColumnUpgrade))
                set3PlyPermaPostUpgrade(json.getString(input3PlyPermaColumnUpgrade).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(input4PlyPermaColumnUpgrade))
                set4PlyPermaPostUpgrade(json.getString(input4PlyPermaColumnUpgrade).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(input8400PermaColumnUpgrade))
                set8400PermaPostUpgrade(json.getString(input8400PermaColumnUpgrade).equals("true"));
            // integer parsing fails on empty strings
            if (json.getString(inputEveSoffitUpgrade).equals(""))
                setEveSoffitUpgrade(0);
            else
                setEveSoffitUpgrade(json.getInt(inputEveSoffitUpgrade));
            // integer parsing fails on empty strings
            if (json.getString(inputGableSoffitUpgrade).equals(""))
                setGableSoffitUpgrade(0);
            else
                setGableSoffitUpgrade(json.getInt(inputGableSoffitUpgrade));
            if (json.has(inputStormBracketUpgrade)) {
                // integer parsing fails on empty strings
                if (json.getString(inputStormBracketUpgrade).equals(""))
                    setStormBracketUpgrade(0);
                else
                    setStormBracketUpgrade(json.getInt(inputStormBracketUpgrade));
            }
            if (json.has(inputStormBracketUpgrade)) {
                // integer parsing fails on empty strings
                if (json.getString(inputXTensionUpgrade).equals(""))
                    setXTensionStrapUpgrade(0);
                else
                    setXTensionStrapUpgrade(json.getInt(inputXTensionUpgrade));
            }
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputShearWallUpgrade))
                setShearWallUpgrade(json.getString(inputShearWallUpgrade).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputKickWallInsulationUpgrade))
                setKickWallInsulationUpgrade(json.getString(inputKickWallInsulationUpgrade).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputInsulationR40Upgrade))
                setInsulationR40Upgrade(json.getString(inputInsulationR40Upgrade).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputInsulationR50Upgrade))
                setInsulationR50Upgrade(json.getString(inputInsulationR50Upgrade).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputInsulationR60Upgrade))
                setInsulationR60Upgrade(json.getString(inputInsulationR60Upgrade).equals("true"));
            // if the box isn't checked on the quote, the inputs won't contain the element
            if (inputs.contains(inputCeilingOnlyUpgrade))
                setCeilingOnlyUpgrade(json.getString(inputCeilingOnlyUpgrade).equals("true"));

        } catch (JSONException e) {
            System.out.println("asdf error converting JSON inputs");
            e.printStackTrace();
        }
    }

    public void setBuildingWidth(int width) { this.width = width; }

    public int getBuildingWidth() { return width; }

    public void setBuildingLength(int length) { this.length = length; }

    public int getBuildingLength() { return length; }

    public void setBuildingHeight(int height) { this.height = height; }

    public int getBuildingHeight() { return height; }

    public void setBuildingType(String buildingType) { this.buildingType = buildingType; }

    public String getBuildingType() { return buildingType; }

    public double getSellingPrice() { return sellingPrice; }

    public void setSellingPrice(double sellingPrice) { this.sellingPrice = sellingPrice; }

    public String getBuildingDetails() { return getBuildingWidth() + "'x" + getBuildingLength() + "'x" + getBuildingHeight() + "' " + getBuildingType(); }

    public boolean getMaterialOnly() { return isMaterialOnly; }

    public void setMaterialOnly(boolean isMaterialOnly) { this.isMaterialOnly = isMaterialOnly; }

    public boolean getWarranty5() { return isWarranty5; }

    public void setWarranty5(boolean isWarranty5) { this.isWarranty5 = isWarranty5; }

    public boolean getBlueprints() { return isBlueprints; }

    public void setBlueprints(boolean isBlueprints) { this.isBlueprints = isBlueprints; }

    public int getSnowLoadLevel() { return snowLoadLevel; }

    public void setSnowLoadLevel(int snowLoadLevel) { this.snowLoadLevel = snowLoadLevel; }

    public int getOccupancyId() { return occupancyId; }

    public void setOccupancyId(int occupancyId) { this.occupancyId = occupancyId; }

    public String getOccupancy() { return occupancy; }

    public void setOccupancy(String occupancy) { this.occupancy = occupancy; }

    public boolean getOilAndGas() { return isOilAndGas; }

    public void setOilAndGas(boolean isOilAndGas) { this.isOilAndGas = isOilAndGas; }

    public double getTrussPrice() { return trussPrice; }

    public void setTrussPrice(double trussPrice) { this.trussPrice = trussPrice; }

    public double getPitch() { return pitch; }

    public void setPitch(double pitch) { this.pitch = pitch; }

    public int getHeelHeight() { return heelHeight; }

    public void setHeelHeight(int heelHeight) { this.heelHeight = heelHeight; }

    public int getDriftLoadRafters() { return driftLoadRaftersQuantity; }

    public void setDriftLoadRafters(int driftLoadRaftersQuantity) { this.driftLoadRaftersQuantity = driftLoadRaftersQuantity; }

    public boolean getDoublePlyRafters() { return isDoublePlyRafters; }

    public void setDoublePlyRafters(boolean isDoublePlyRafters) { this.isDoublePlyRafters = isDoublePlyRafters; }

    public boolean getPostDiscs() { return isPostDiscs; }

    public void setPostDiscs(boolean isPostDiscs) { this.isPostDiscs = isPostDiscs; }

    public int getWallTypeId() { return wallTypeId; }

    public void setWallTypeId(int wallTypeId) { this.wallTypeId = wallTypeId; }

    public String getWallType() { return wallType; }

    public void setWallType(String wallType) { this.wallType = wallType; }

    public int getEvePostSpacing() { return evePostSpacing; }

    public void setEvePostSpacing(int evePostSpacing) { this.evePostSpacing = evePostSpacing; }

    public int getGablePostSpacing() { return gablePostSpacing; }

    public void setGablePostSpacing(int gablePostSpacing) { this.gablePostSpacing = gablePostSpacing; }

    public int getGableVents() { return gableVents; }

    public void setGableVents(int gableVents) { this.gableVents = gableVents; }

    public int getEveSoffitLength() { return eveSoffitLength; }

    public void setEveSoffitLength(int eveSoffitLength) { this.eveSoffitLength = eveSoffitLength; }

    public boolean getStormBrackets() { return stormBrackets; }

    public void setStormBrackets(boolean stormBrackets) { this.stormBrackets = stormBrackets; }

    public int getStormBracketQuantity() { return stormBracketQuantity; }

    public void setStormBracketQuantity(int stormBracketQuantity) { this.stormBracketQuantity = stormBracketQuantity; }

    public int getSmokeStops() { return smokeStops; }

    public void setSmokeStops(int smokeStops) { this.smokeStops = smokeStops; }

    public int getGableSoffitLength() { return gableSoffitLength; }

    public void setGableSoffitLength(int gableSoffitLength) { this.gableSoffitLength = gableSoffitLength; }

    public boolean getXTensionStraps() { return xTensionStraps; }

    public void setXTensionStraps(boolean xTensionStraps) { this.xTensionStraps = xTensionStraps; }

    public int getXTensionStrapQuantity() { return xTensionStrapQuantity; }

    public void setXTensionStrapQuantity(int xTensionStrapQuantity) { this.xTensionStrapQuantity = xTensionStrapQuantity; }

    public int getGableStops() { return gableStops; }

    public void setGableStops(int gableStops) { this.gableStops = gableStops; }

    public int getTightSiteEve() { return tightSiteEve; }

    public void setTightSiteEve(int tightSiteEve) { this.tightSiteEve = tightSiteEve; }

    public String getRidge() { return ridge; }

    public void setRidge(String ridge) { this.ridge = ridge; }

    public int getFireStops() { return fireStops; }

    public void setFireStops(int fireStops) { this.fireStops = fireStops; }

    public int getTightSiteGable() { return tightSiteGable; }

    public void setTightSiteGable(int tightSiteGable) { this.tightSiteGable = tightSiteGable; }

    public boolean getInsulated() { return insulated; }

    public void setInsulated(boolean insulated) { this.insulated = insulated; }

    public int getInsulationWidth() { return insulationWidth; }

    public void setInsulationWidth(int insulationWidth) { this.insulationWidth = insulationWidth; }

    public int getInsulationLength() { return insulationLength; }

    public void setInsulationLength(int insulationLength) { this.insulationLength = insulationLength; }

    public boolean getCeilingOnly() { return ceilingOnly; }

    public void setCeilingOnly(boolean ceilingOnly) { this.ceilingOnly = ceilingOnly; }

    public int getCeilingWidth() { return ceilingWidth; }

    public void setCeilingWidth(int ceilingWidth) { this.ceilingWidth = ceilingWidth; }

    public int getCeilingLength() { return ceilingLength; }

    public void setCeilingLength(int ceilingLength) { this.ceilingLength = ceilingLength; }

    public int getInsulationDensity() { return insulationDensity; }

    public void setInsulationDensity(int insulationDensity) { this.insulationDensity = insulationDensity; }

    public int getAtticHatches() { return atticHatches; }

    public void setAtticHatches(int atticHatches) { this.atticHatches = atticHatches; }

    public int getAdditionalAtticHatches() { return additionalAtticHatches; }

    public void setAdditionalAtticHatches(int additionalAtticHatches) { this.additionalAtticHatches = additionalAtticHatches; }

    public boolean getCodeBoard() { return codeBoard; }

    public void setCodeBoard(boolean codeBoard) { this.codeBoard = codeBoard; }

    public int getAccentColour() { return colourAccent; }

    public void setAccentColour(int colourAccent) { this.colourAccent = colourAccent; }

    public int getWallMetalColour() { return colourWallMetal; }

    public void setWallMetalColour(int atticHatches) { this.atticHatches = atticHatches; }

    public int getGableMetalColour() { return colourGableMetal; }

    public void setGableMetalColour(int colourWallMetal) { this.colourWallMetal = colourWallMetal; }

    public int getRoofColour() { return colourRoofMetal; }

    public void setRoofColour(int colourRoofMetal) { this.colourRoofMetal = colourRoofMetal; }

    public int getTrimColour() { return colourTrimMetal; }

    public void setTrimColour(int colourTrimMetal) { this.colourTrimMetal = colourTrimMetal; }

    public int getFoldingDoorColour() { return colourFoldingDoor; }

    public void setFoldingDoorColour(int colourFoldingDoor) { this.colourFoldingDoor = colourFoldingDoor; }

    public int getSlidingDoorColour() { return colourSlidingDoor; }

    public void setSlidingDoorColour(int colourSlidingDoor) { this.colourSlidingDoor = colourSlidingDoor; }

    public int getSoffitColour() { return colourSoffit; }

    public void setSoffitColour(int colourSoffit) { this.colourSoffit = colourSoffit; }

    public int getWainscotingColour() { return colourWainscoting; }

    public void setWainscotingColour(int colourWainscoting) { this.colourWainscoting = colourWainscoting; }

    public int getEveAccentQuantity() { return eveAccentQuantity; }

    public void setEveAccentQuantity(int eveAccentQuantity) { this.eveAccentQuantity = eveAccentQuantity; }

    public int getGableAccentQuantity() { return gableAccentQuantity; }

    public void setGableAccentQuantity(int gableAccentQuantity) { this.gableAccentQuantity = gableAccentQuantity; }

    public String getPromotionalCode() { return promotionalCode; }

    public void setPromotionalCode(String promotionalCode) { this.promotionalCode = promotionalCode; }

    public int getWebLaterals() { return webLaterals; }

    public void setWebLaterals(int webLaterals) { this.webLaterals = webLaterals; }

    public int getBottomCordSpacing() { return bottomCordSpacing; }

    public void setBottomCordSpacing(int bottomCordSpacing) { this.bottomCordSpacing = bottomCordSpacing; }

    public boolean getTestQuote() { return isTestQuote; }

    public void setTestQuote(boolean isTestQuote) { this.isTestQuote = isTestQuote; }

    public boolean getTradeShowQuote() { return isTradeShowQuote; }

    public void setTradeShowQuote(boolean isTradeShowQuote) { this.isTradeShowQuote = isTradeShowQuote; }

    public String getOverheadDoors() { return overheadDoorsJson; }

    public void setOverheadDoors(String overheadDoorsJson) { this.overheadDoorsJson = overheadDoorsJson; }

    public String getSlidingDoors() { return slidingDoorsJson; }

    public void setSlidingDoors(String slidingDoorsJson) { this.slidingDoorsJson = slidingDoorsJson; }

    public String getFoldingDoors() { return foldingDoorsJson; }

    public void setFoldingDoors(String foldingDoorsJson) { this.foldingDoorsJson = foldingDoorsJson; }

    public String getManDoors() { return manDoorsJson; }

    public void setManDoors(String manDoorsJson) { this.manDoorsJson = manDoorsJson; }

    public String getWindows() { return windowsJson; }

    public void setWindows(String windowsJson) { this.windowsJson = windowsJson; }

    public String getCustomWindows() { return customWindowsJson; }

    public void setCustomWindows(String customWindowsJson) { this.customWindowsJson = customWindowsJson; }

    public String getWallLights() { return wallLightJson; }

    public void setWallLights(String wallLightJson) { this.wallLightJson = wallLightJson; }

    public String getKickWall() { return kickWallJson; }

    public void setKickWall(String kickWallJson) { this.kickWallJson = kickWallJson; }

    public String getPartitionWalls() { return partitionWallJson; }

    public void setPartitionWalls(String partitionWallJson) { this.partitionWallJson = partitionWallJson; }

    public String getMezzanines() { return mezzanineJson; }

    public void setMezzanines(String mezzanineJson) { this.mezzanineJson = mezzanineJson; }

    public String getLeanTos() { return leanToJson; }

    public void setLeanTos(String leanToJson) { this.leanToJson = leanToJson; }

    public String getCustoms() { return customsJson; }

    public void setCustoms(String customsJson) { this.customsJson = customsJson; }

    public String getMaterials() {
        return materials;
    }

    public void setMaterials(String materials) {
        this.materials = materials;
    }

    public int getStairsNoTurns() {
        return stairsNoTurns;
    }

    public void setStairsNoTurns(int stairsNoTurns) {
        this.stairsNoTurns = stairsNoTurns;
    }

    public int getStairsOneTurn() {
        return stairsOneTurn;
    }

    public void setStairsOneTurn(int stairsOneTurn) {
        this.stairsOneTurn = stairsOneTurn;
    }

    public int getStairsTwoTurns() {
        return stairsTwoTurns;
    }

    public void setStairsTwoTurns(int stairsTwoTurns) {
        this.stairsTwoTurns = stairsTwoTurns;
    }

    public boolean get3PlyPermaPostUpgrade() {
        return is3PlyPermaPostUpgrade;
    }

    public void set3PlyPermaPostUpgrade(boolean is3PlyPermaPostUpgrade) {
        this.is3PlyPermaPostUpgrade = is3PlyPermaPostUpgrade;
    }

    public boolean get4PlyPermaPostUpgrade() {
        return is4PlyPermaPostUpgrade;
    }

    public void set4PlyPermaPostUpgrade(boolean is4PlyPermaPostUpgrade) {
        this.is4PlyPermaPostUpgrade = is4PlyPermaPostUpgrade;
    }

    public boolean get8400PermaPostUpgrade() {
        return is8400PermaPostUpgrade;
    }

    public void set8400PermaPostUpgrade(boolean is8400PermaPostUpgrade) {
        this.is8400PermaPostUpgrade = is8400PermaPostUpgrade;
    }

    public int getEveSoffitUpgrade() {
        return eveSoffitUpgradeLength;
    }

    public void setEveSoffitUpgrade(int eveSoffitUpgradeLength) {
        this.eveSoffitUpgradeLength = eveSoffitUpgradeLength;
    }

    public int getGableSoffitUpgrade() {
        return gableSoffitUpgradeLength;
    }

    public void setGableSoffitUpgrade(int gableSoffitUpgradeLength) {
        this.gableSoffitUpgradeLength = gableSoffitUpgradeLength;
    }

    public int getStormBracketUpgrade() {
        return stormBracketUpgradeQuantity;
    }

    public void setStormBracketUpgrade(int stormBracketUpgradeQuantity) {
        this.stormBracketUpgradeQuantity = stormBracketUpgradeQuantity;
    }

    public int getXTensionStrapUpgrade() {
        return xTensionStrapsUpgradeQuantity;
    }

    public void setXTensionStrapUpgrade(int xTensionStrapsUpgradeQuantity) {
        this.xTensionStrapsUpgradeQuantity = xTensionStrapsUpgradeQuantity;
    }

    public boolean getShearWallUpgrade() {
        return isShearWallUpgrade;
    }

    public void setShearWallUpgrade(boolean isShearWallUpgrade) {
        this.isShearWallUpgrade = isShearWallUpgrade;
    }

    public boolean getKickWallInsulationUpgrade() {
        return isKickWallInsulationUpgrade;
    }

    public void setKickWallInsulationUpgrade(boolean isKickWallInsulationUpgrade) {
        this.isKickWallInsulationUpgrade = isKickWallInsulationUpgrade;
    }

    public boolean getInsulationR40InsulationUpgrade() {
        return isInsulationR40Upgrade;
    }

    public void setInsulationR40Upgrade(boolean isInsulationR40Upgrade) {
        this.isInsulationR40Upgrade = isInsulationR40Upgrade;
    }

    public boolean getInsulationR50InsulationUpgrade() {
        return isInsulationR50Upgrade;
    }

    public void setInsulationR50Upgrade(boolean isInsulationR50Upgrade) {
        this.isInsulationR50Upgrade = isInsulationR50Upgrade;
    }

    public boolean getInsulationR60InsulationUpgrade() {
        return isInsulationR60Upgrade;
    }

    public void setInsulationR60Upgrade(boolean isInsulationR60Upgrade) {
        this.isInsulationR60Upgrade = isInsulationR60Upgrade;
    }

    public boolean getCeilingOnlyUpgrade() {
        return isCeilingOnlyUpgrade;
    }

    public void setCeilingOnlyUpgrade(boolean isCeilingOnlyUpgrade) {
        this.isCeilingOnlyUpgrade = isCeilingOnlyUpgrade;
    }

    public int getQuantifyOfQuoteProduct(int productId)
    {
        int value = 0;
        JSONObject materials = null;
        JSONObject material;

        try {
            // create JSON object from JSON string
            materials = new JSONObject(getMaterials());

/*
                Iterator<String> keys = materials.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    Object v = materials.get(key);
                    System.out.println("asdf key: " + key + ", value: " + v.toString());
                }
*/
            int quantity = 0;
            // create a JSON object we can reference on this row
            material = new JSONObject(materials.get(String.valueOf(productId)).toString());
            // use the JSON object to get the actual quantity array string
            String quantitiesString = material.getString("quantity");
            // remove the extra array characters
            quantitiesString = quantitiesString
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");
            // create an array list from the comman delimited string of quantities
            List<String> quantitiesList = new ArrayList<String>(Arrays.asList(quantitiesString.split(",")));
            // loop through array and add up all the quantities
            for (int i = 0; i < quantitiesList.size(); i++)
                quantity =+ Integer.parseInt(quantitiesList.get(i));

            // set our return value to the total quantity
            if (quantity > 0)
                value = quantity;

        } catch (JSONException e) {
            System.out.println("asdf error in getQuantityOfQuoteProduct: " + e.toString());
            // Something went wrong!
            try {
                return getQuantityOfProduct(productId);
            } catch (JSONException e1) {
                System.out.println("asdf get product quantity error: " + e.toString());
                e1.printStackTrace();
            }
        }

        return value;
    }

    public Double calculateQuotePrice()
    {

        long startTime = System.currentTimeMillis();
        System.out.println("asdf current time: " + startTime);
        // this simply calculates the price of the new quote
        Double price = 0.0;
        JSONObject materials;
        JSONObject material;
     //   String columnPrice = "price";
        String columnPrice = "unit_price";
        String columnId = "product_id";
        String columnCalculationId = "total_price_calculation_id";

        // on initial page load this will not be set
        if (getMaterials() == null) {
            // retrieve saved price from database if we're loading a saved quote
            return getPrice();
        }
        System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));

        try {
            // create JSON object from JSON string
            materials = new JSONObject(getMaterials()); // returns JSON string of all materials and attributes
            System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));

            Iterator<String> keys = materials.keys();
            System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));
            while (keys.hasNext()) {
                System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));
                String key = keys.next();
                System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));
                Object v = materials.get(key);
                System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));
                material = new JSONObject(v.toString());
                System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));

                // for each material, get the calculation type and find the total price
                // different materials have prices calculated in different ways
                switch(material.getInt(columnCalculationId)){
                    case 0:
                        // report error
                        break;
                    case 1: // Q x P
                        System.out.println("asdf time elapsedd8: " + (System.currentTimeMillis() - startTime));
                        int quantity = getQuantityOfProduct(material.getInt(columnId));
                        System.out.println("asdf time elapsedd9: " + (System.currentTimeMillis() - startTime));
                        double unitPrice =
                            Double.parseDouble(material.getString(columnPrice)
                                .replace("[", "")
                                .replace("]", "")
                                .replace("\"", ""));
                        System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));
                        price += quantity * unitPrice;
                        break;
                    case 2: // lumber
                        break;
                    case 3: // P x W x L x Q
                        break;
                    default:
                        break;
                }

            }

        } catch (JSONException e) {
            // Something went wrong!
            System.out.println("asdf error in calculateQuotePrice: " + e.toString());
        }

        System.out.println("asdf time elapsedd: " + (System.currentTimeMillis() - startTime));
        return price;
    }

    public int getQuantityOfProduct(int productId) throws JSONException {
        int quantity = 0;
        int squareFootage = 0;
        JSONArray items = null;

        //      System.out.println("Asdf product: " + productId);

        switch (productId) {
            case 1: // 3x5 fixed window
                try {
                    JSONArray windows = new JSONArray(getWindows());
                    // loop through each window the user added to the building
                    for (int i = 0; i < windows.length(); i++) {
                        // deal with one window at a time
                        JSONObject window = windows.getJSONObject(i);
                        // if the window is set to customer supplied, it is a zero quantity
                        if (window.getString("customer_supplied") != "true" && window.getInt("type") == 1)
                            quantity += Integer.parseInt(window.getString("quantity"));
                    }
                } catch (JSONException e) {
                    System.out.println("Asdf error: " + e.toString());
                    e.printStackTrace();
                    return 0;
                }
                break;
            case 2: // quality management
                quantity = getMaterialOnly() ? 0 : 1;
                break;
            case 3: // custom materials
                // create JSON object from JSON string
                try {
                    JSONArray customs = new JSONArray(getCustoms());
                    for (int i = 0; i < customs.length(); i++) {
                        JSONObject custom = customs.getJSONObject(i);
                        if (custom.getString("included") == "true")
                            quantity += Integer.parseInt(custom.getString("materials"));
                    }
                } catch (JSONException e) {
                    System.out.println("Asdf error: " + e.toString());
                    e.printStackTrace();
                    return 0;
                }
                break;
            case 4: // custom labour
                if (getMaterialOnly())
                    break;

                // create JSON object from JSON string
                try {
                    JSONArray customs = new JSONArray(getCustoms());
                    for (int i = 0; i < customs.length(); i++) {
                        JSONObject custom = customs.getJSONObject(i);
                        if (custom.getString("included") == "true")
                            quantity += Integer.parseInt(custom.getString("labour"));
                    }
                } catch (JSONException e) {
                    System.out.println("Asdf error: " + e.toString());
                    e.printStackTrace();
                    return 0;
                }
                break;
            case 5: // peak sign
                quantity = 2;
                break;
            case 6: // exterior height labour premium
                if (getMaterialOnly())
                    break;

                if (getBuildingHeight() >= 16)
                    quantity = ((getBuildingHeight() - 16) / 2) * getBuildingWidth() * getBuildingLength();
                break;
            case 7: // interior height labour premium
                if (getInsulated() && getBuildingHeight() >= 16 && !getMaterialOnly())
                    quantity = ((getBuildingHeight() - 16) / 2) * getInsulationWidth() * getInsulationLength();
                break;
            case 8: // 3/4" Plywood
                int osbSquareFootagePerSheet = 16;
                JSONArray foldingDoors = new JSONArray(getFoldingDoors());
                for (int i = 0; i < foldingDoors.length(); i++) {
                    JSONObject door = foldingDoors.getJSONObject(i);
                    if (door.getString("shear-wall") == "true")
                        quantity = door.getInt("quantity") * (getBuildingWidth() - door.getInt("width")) * getBuildingHeight() / osbSquareFootagePerSheet;
                }
                break;
            case 9: // Shear Wall Labour
                if (getMaterialOnly())
                    break;

                items = new JSONArray(getFoldingDoors());
                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    if (item.getString("shear-wall") == "true")
                        quantity += item.getInt("quantity") * (getBuildingWidth() - item.getInt("width")) * getBuildingHeight();
                }
                break;
            case 10: // exterior labour 8600+
                if (getMaterialOnly())
                    break;

                squareFootage = getBuildingWidth() * getBuildingLength();
                quantity += squareFootage >= 8600 ? squareFootage : 0;
                break;
            case 11: // interior labour 8600+
                if (getMaterialOnly())
                    break;

                squareFootage = getInsulationWidth() * getInsulationLength();
                quantity += squareFootage >= 8600 ? squareFootage : 0;
                break;
            case 12: // X-Tension Straps
                JSONObject inputs = new JSONObject(getInputs());
                if (inputs.getString("x-tension-quantity").equals("") || inputs.getString("x-tension-quantity").equals("0"))
                {
                    quantity += getBuildingHeight() >= 16 ? 4 : 0;
                    if (inputs.getString("x-tension").equals("true"))
                    {
                        items = new JSONArray(getFoldingDoors());
                        for (int i = 0; i < items.length(); i++) {
                            JSONObject item = items.getJSONObject(i);
                            if (item.getString("shear-wall").equals("true"))
                                quantity -= 2 * item.getInt("quantity");
                        }
                    }
                }
                else
                    quantity += Integer.parseInt(inputs.getString("x-tension-quantity"));

                quantity = Math.max(quantity, 0);
                break;
            case 13: // poly carbonate panel
                items = new JSONArray(getFoldingDoors());
                for (int i = 0; i < items.length(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    if (item.getString("poly-carbonate").equals("true"))
                        quantity += item.getInt("quantity") * item.getInt("width");
                }
                break;
            case 14:
                quantity = 1;
                break;
            case 284:
                quantity = 3;
                break;
            default:
                quantity = 0;
                break;
        }

        return quantity;
    }

    public void addOverheadDoor(String quantity, String width, String height, String location, String operator, String windowInserts, String bowStrap, String customerSupplied)
    {
        JSONObject overhead = new JSONObject();
        String overheads = getOverheadDoors();

        try {
            JSONArray overheadJsonArray = new JSONArray(overheads);

            overhead.put("quantity", quantity);
            overhead.put("width", width);
            overhead.put("height", height);
            overhead.put("location", location);
            overhead.put("operator", operator);
            overhead.put("window_inserts", windowInserts);
            overhead.put("bow_strap", bowStrap);
            overhead.put("customer_supplied", customerSupplied);

            overheadJsonArray.put(overhead);
            setOverheadDoors(overheadJsonArray.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void addSlidingDoor(String quantity, String width, String height, String location)
    {
        JSONObject sliding = new JSONObject();
        String slidings = getSlidingDoors();

        try {
            JSONArray slidingJsonArray = new JSONArray(slidings);

            sliding.put("quantity", quantity);
            sliding.put("width", width);
            sliding.put("height", height);
            sliding.put("location", location);

            slidingJsonArray.put(sliding);
            setSlidingDoors(slidingJsonArray.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void addFoldingDoor(String quantity, String width, String height, String insulated, String lock, String windows, String power, String columnSupports, String jTrack, String polyCarbonate, String shearWall)
    {
        JSONObject folding = new JSONObject();
        String foldings = getFoldingDoors();

        try {
            JSONArray foldingJsonArray = new JSONArray(foldings);

            folding.put("quantity", quantity);
            folding.put("width", width);
            folding.put("height", height);
            folding.put("insulated", insulated);
            folding.put("lock", lock);
            folding.put("column_supports", columnSupports);
            folding.put("jtrack", jTrack);
            folding.put("poly-carbonate", polyCarbonate);
            folding.put("shear-wall", shearWall);
            folding.put("power", power);
            folding.put("windows", windows);

            foldingJsonArray.put(folding);
            setFoldingDoors(foldingJsonArray.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
 
Upvote 0
I must be doing it wrong because my profiler just shows me CPU, memory and network usage. I don't see anything for looking into certain functions, how do I do that?

Since I'm a web developer, I'm used to having to print things out to the screen in order to see them so I was using System.out and filtering the outputs to only display results containing asdf. I'll try it with the log and see if I can figure that out, thanks!
 
Upvote 0
Oh yes, you can see the System.out in the Logcat, that's how I view it. I change the output to verbose and filter by asdf.
I'm still trying to figure out how to make the profiler specific to a function though, how do I do anything other than view the CPU usage? I can't seem to modify how it works.

And thanks a lot by the way, you're a huge help.
 
Upvote 0
You have to start a recording session, and it will log the time spent in method calls.
I haven't had cause to use this myself, but it's similar to other profilers I've used, and appears to have all the necessary features to be useful.

https://developer.android.com/studio/profile/cpu-profiler

If for some reason, that fails to deliver, then your code's log output should be a good indication of where the execution time is spent.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones