Samples

To see our APIs in action, look at the clover-android-sdk-examples directory in the Clover Android SDK repository. You can find examples that use the Clover APIs to connect to the various Services, query Clover ContentProviders, and fetch data directly from the Clover REST API.

Android Examples

In addition to the code snippets below, please see more of our examples in our Android Examples Repository.

Querying Inventory

In InventoryListActivity, the Clover Inventory ContentProvider is queried to display a list of the merchant’s inventory. The merchant’s currency is also retrieved to correctly format prices.

1. Get a Clover Account:

private Account mAccount;
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  mAccount = CloverAccount.getAccount(this);

 

2. Then get the merchant’s Currency using MerchantConnector to get a Merchant:

mMerchantConnector = new MerchantConnector(this, mAccount, null);
mMerchantConnector.getMerchant(new ServiceConnector.Callback<Merchant>() {
  @Override
  public void onServiceSuccess(Merchant result, ResultStatus status) {
    // set the Currency
    sCurrencyFormat.setCurrency(result.getCurrency());
    // now start the Loader to query Inventory
    getLoaderManager().initLoader(ITEM_LOADER_ID, null, InventoryListActivity.this);
  }
  @Override
  public void onServiceFailure(ResultStatus status) {
  }
  @Override
  public void onServiceConnectionFailure() {
  }
});

 

3. Once we have the Currency, a CursorLoader is used to to query the ContentProvider:

getLoaderManager().initLoader(ITEM_LOADER_ID, null, InventoryListActivity.this);

 

4. And in onCreateLoader return the CursorLoader as follows:

return new CursorLoader(this, InventoryContract.Item.contentUriWithAccount(mAccount), null, null, null, InventoryContract.Item.PRICE);

 

5. Once the query is complete, retrieve the inventory item’s data from the cursor and display using a SimpleCursorAdapter. A ViewBinder is set to format the price into a String using the merchant’s Currency.

adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
      @Override
      public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        if (view.getId() == android.R.id.text2) {
          TextView priceTextView = (TextView) view;
          String price = "";
          PriceType priceType = PriceType.values()[cursor.getInt(cursor.getColumnIndex(InventoryContract.Item.PRICE_TYPE))];
          String priceString = cursor.getString(cursor.getColumnIndex(InventoryContract.Item.PRICE));
          long value = Long.valueOf(priceString);
          if (priceType == PriceType.FIXED) {
            price = sCurrencyFormat.format(value / 100.0);
          } else if (priceType == PriceType.VARIABLE) {
            price = "Variable";
          } else if (priceType == PriceType.PER_UNIT) {
            price = sCurrencyFormat.format(value / 100.0) + "/" + cursor.getString(cursor.getColumnIndex(InventoryContract.Item.UNIT_NAME));
          }
          priceTextView.setText(price);
          return true;
        }
        return false;
      }
    });

Building an Order

It is possible to use the OrderConnector to create orders and then associate them with the relevant LineItems, Discounts, Modifiers, and other related objects.

1. Get a Clover Account:

private Account mAccount;
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  mAccount = CloverAccount.getAccount(this);

 

2. Use the OrderConnector and InventoryConnector to establish persistent connections (Remember to disconnect both Connectors once your work is done – See step 9):

if (mAccount != null) {
  orderConnector = new OrderConnector(this, mAccount, null);
  orderConnector.connect();
  inventoryConnector = new InventoryConnector(this, mAccount, null);
  inventoryConnector.connect();
}

 

NOTE:  Once your connections are in place, the work of interacting with merchant data (steps 4-8) should be completed on an asynchronous thread. 

4. Use the orderConnector to create a new order:

mOrder = orderConnector.createOrder(new Order());

 

5. Use the inventoryConnector to get an Item, and then use the Item to add a LineItem to the order. Note that fixed-price, per-unit, and variable-price items each have separate add methods.

merchantItems = inventoryConnector.getItems();

mItem = merchantItems.get(itemId);

if (mItem.getPriceType() == PriceType.FIXED) {
    mLineItem = orderConnector.addFixedPriceLineItem(mOrder.getId(), mItem.getId(), null, null);
} else if (mItem.getPriceType() == PriceType.PER_UNIT) {
    mLineItem = orderConnector.addPerUnitLineItem(mOrder.getId(), mItem.getId(), 1, null, null);
} else { // The item must be of a VARIABLE PriceType
    mLineItem = orderConnector.addVariablePriceLineItem(mOrder.getId(), mItem.getId(), 5, null, null);
}

 

6. Discounts can be created separately:

//Percentage discount
final com.clover.sdk.v3.order.Discount discount1 = new Discount();
discount1.setPercentage(10l);
discount1.setName("Example 10% Discount");

//Static discount
final Discount discount2 = new Discount();
discount2.setAmount(-100l);
discount2.setName("Example 1 base unit of currency Discount");

 

7. Once created, discounts can be applied to entire orders or to individual line items:

//Apply first discount to whole order
orderConnector.addDiscount(mOrder.getId(), discount1);

//Apply second discount only to the first line item
orderConnector.addLineItemDiscount(mOrder.getId(), mLineItem.getId(), discount2);

 

8. Use the inventoryConnector to retrieve ModifierGroups and their Modifiers, in order to apply Modifiers to the relevant lineItems:

List<ModifierGroup> modifierGroups = inventoryConnector.getModifierGroupsForItem(mItem.getId());

//Check if any modifier is available to the item
if (modifierGroups.size() > 0){
    List<Modifier> modifiers = modifierGroups.get(0).getModifiers();
    if (modifiers.size() > 0){
        //If so, apply the first modifier to the line item
        orderConnector.addLineItemModification(mOrder.getId(), mLineItem.getId(), modifiers.get(0));
    }
}

 

9. Finally, once your asynchronous task is finished, remember to disconnect from unneeded connectors:

if (orderConnector != null) {
    orderConnector.disconnect();
    orderConnector = null;
}
if (inventoryConnector != null) {
    inventoryConnector.disconnect();
    inventoryConnector = null;
}

Querying Web Service

WebServiceActivity shows how the Clover REST API can be queried directly once the Clover Account and auth token are retrieved.

1. Get a Clover Account:

private Account mAccount;
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  mAccount = CloverAccount.getAccount(this);

 

2. Get your app’s auth token using the CloverAuth.authenticate call in a background thread:

CloverAuth.AuthResult authResult = CloverAuth.authenticate(WebServiceActivity.this, mAccount);

 

3. If successful, the AuthResult now contains the authToken and baseUrl.

Query the REST API to get the merchant id and the get inventory items using the included CustomHttpClient:

CustomHttpClient httpClient = CustomHttpClient.getHttpClient();
// first we get the merchant id
String getNameUri = "/v2/merchant/name";
String url = authResult.baseUrl + getNameUri + "?access_token=" + authResult.authToken;
String result = httpClient.get(url);
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject root = (JSONObject) jsonTokener.nextValue();
String merchantId = root.getString("merchantId");
// now we get inventory items using the merchant id
String inventoryUri = "/v2/merchant/" + merchantId + "/inventory/items";
url = authResult.baseUrl + inventoryUri + "?access_token=" + authResult.authToken;
result = httpClient.get(url);