Apigo Platform Documentation for Android App | Apigo.id

Apigo Starter Project for Android Documentation

Last updated: May 23th, 2018

Getting Started

A library that gives you access to the powerful Apigo cloud platform from your Android app. For more information about Apigo and its features, see Apigo Website and Apigo Documentations.

Download
  1. Download the latest AAR and copy it on libs directory.
  2. Define in your app module build.gradle this code below before dependencies

repositories{
    flatDir {
        dirs 'libs'
    }
}

Then add this code below on dependencies :


implementation(name: 'Apigo-Android-1.0.0', ext: 'aar')
implementation 'com.squareup.okhttp3:okhttp:3.9.1'

Setup
  1. Register first to Apigo Customer Portal
  2. Create an application to get applicationId and clientKey
  3. Add this line below to your Application class within onCreate method to initialize Apigo SDK

Apigo.initialize(this,
                "YOUR_SERVER_URL",
                "YOUR_APPLICATION_ID",
                "YOUR_CLIENT_KEY");

Don't forget to initialize your application class to AndroidManifest.xml

(Optional) You can add some custom setup :

  • Enable Apigo SDK debug logging by calling Apigo.setLogLevel(int); before initialize SDK.
  • Apigo Log Level Mode : LOG_LEVEL_VERBOSE, LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, LOG_LEVEL_WARNING, LOG_LEVEL_ERROR, LOG_LEVEL_NONE

Everything is done!

Object

Managing Objects

Storing data on Apigo is built around the ApigoObject. Each ApigoObject contains key-value pairs of JSON-compatible data. This data is using schema, which means that you need to specify ahead of time what keys exist on each ApigoObject from our Apigo Cloud. Then you can simply set a key-value pairs you want to save, and our backend will store it.

For example, let's say you set a Beacon parameters. A single ApigoObject could contain :


{
    "isActive":true, 
    "major":1, 
    "name":"Beacon One", 
    "minor":284, 
    "proximityUUID":"CB10023F-A318-3394-4199-A8730C7C1AEC"
}

Keys must be alphanumeric strings. Values can be String, Number, Date, Boolean, or even Array and Object - anything that can be JSON-encoded.

Saving Objects

Let’s say you want to save the Beacon described above to the Apigo Cloud. The interface is similar to a Map, plus the saveInBackground method:


ApigoObject data = new ApigoObject("Beacon");
// set data
data.put("name", "Beacon One");
data.put("proximityUUID", "CB10023F-A318-3394-4199-A8730C7C1AEC");
data.put("major", 1);
data.put("minor", 284);
data.put("isActive", true);
data.put("timestamp", new Date());
// execute save data
data.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // data saved, show success message
    }
});

Retrieve an Object

If you need to fetch a data with the latest data that is in the cloud, you can call the fetchInBackground method like so:


// create data from existing objecId
ApigoObject data = ApigoObject.createWithoutData("Beacon", "objectId");
// fetching the data
data.fetchInBackground(new GetCallback() {
    @Override
    public void done(ApigoObject object, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // fetch data succeeded
    }
});

To get the values out of the ApigoObject, there’s a getX method for each data type:


boolean isActive = data.getBoolean("isActive"); 
int major = data.getInt("major"); 
String name = data.getString("name"); 
int minor = data.getInt("minor"); 
String proximityUUID = data.getString("proximityUUID");

If you don’t know what type of data you’re getting out, you can call get(key), but then you probably have to cast it right away anyways. In most situations you should use the typed accessors like getString.

The three special values have their own accessors:


String objectId = data.getObjectId();
Date updatedAt = data.getUpdatedAt();
Date createdAt = data.getCreatedAt();

Updating Objects

After getting the data, you can update your data that stored in cloud using method saveInBackground.


ApigoObject data; // fetched data
// set data
data.setData("name", "Beacon Two");
data.setData("proximityUUID", "CB10023F-A318-3394-4199-A8730C7C1AEC");
data.setData("major", 2);
data.setData("minor", 284);
data.setData("isActive", false);
data.setData("timestamp", new Date());
// execute save data
data.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // data updated, show success message
    }
});

Deleting Object

To delete a data from the Apigo Cloud, use method deleteInBackground:


ApigoData data;
data.deleteInBackground(new DeleteCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // data deleted successfully
    }
});

Data Types

So far we’ve used values with type String, Integer, boolean. Apigo also supports float, java.util.Date, and JSONObject.NULL
You can nest JSONObject and JSONArray objects to store more structured data within a single ApigoObject. Overall, the following types are allowed for each field in your object:

  • String => String
  • Number => primitive numeric values such as int, double, long, or float
  • Bool => boolean
  • Array => JSONArray
  • Object => JSONObject
  • Date => java.util.Date
  • Null => JSONObject.NULL

Some examples:


int myNumber = 42;
String myString = "the number is " + myNumber;
Date myDate = new Date();

JSONArray myArray = new JSONArray();
myArray.put(myString);
myArray.put(myNumber);

JSONObject myObject = new JSONObject();
myObject.put("number", myNumber);
myObject.put("string", myString);

ApigoObject bigObject = new ApigoObject("BigObject");
bigObject.put("myNumber", myNumber);
bigObject.put("myString", myString);
bigObject.put("myDate", myDate);
bigObject.put("myArray", myArray);
bigObject.put("myObject", myObject);
bigObject.put("myNull", JSONObject.NULL);
bigObject.saveInBackground();

Query

Managing Queries

There are many other ways to retrieve data with Apigo Query. You can retrieve many data at once, put conditions on the data you wish to retrieve.

Basic Query

In many cases, there is a condition that need to specify which datas you want to retrieve. The ApigoQuery offers different ways to retrieve a list of datas. The general pattern is to create a ApigoQuery, put conditions on it, and then retrieve a List of matching ApigoObjects using the findInBackground method with a FindCallback.

For example, to retrieve Beacon data with a name, use the whereEqualTo method to constrain the value for a key:


ApigoQuery query = ApigoQuery.getQuery("Beacon");
query.whereEqualTo("name", "Beacon One");
query.findInBackground(new FindCallback() {
    @Override
    public void done(List list, ApigoException e) {
        if (e != null) {
            // exception happen, handle the message
            return;
        } 

        // found the beacons, show in listview
    }
});

Query Constraint

There are several ways to put constraints on the datas found by a ApigoQuery. You can filter out datas with a particular key-value pair with whereNotEqualTo:


query.whereNotEqualTo("name", "Beacon One");

You can give multiple constraints, and datas will only be in the results if they match all of the constraints. In other words, it’s like an AND of constraints.


query.whereNotEqualTo("name", "Beacon One");
query.whereGreaterThan("major", 1);

You can limit the number of results with setLimit. By default, results are limited to 100, but anything from 1 to 1000 is a valid limit:


query.setLimit(20); // limit to at most 20 results

You can skip the first results with setSkip. This can be useful for pagination:


query.setSkip(10); // skip the first 10 results

For sortable types like numbers and strings, you can control the order in which results are returned:


// Sorts the results in ascending order by the beacon's major
query.orderByAscending("major");

// Sorts the results in descending order by the beacon's minor
query.orderByDescending("minor");

You can add more sort keys to the query as follows:


// Sorts the results in ascending order by the beacon's major field if the previous sort keys are equal.
query.addAscendingOrder("major");

// Sorts the results in descending order by the beacon's minor field if the previous sort keys are equal.
query.addDescendingOrder("minor");

For sortable types, you can also use comparisons in queries:


// Restricts to major < 123
query.whereLessThan("major", 123);

// Restricts to major <= 123
query.whereLessThanOrEqualTo("major", 123);

// Restricts to major > 123
query.whereGreaterThan("major", 123);

// Restricts to major >= 123
query.whereGreaterThanOrEqualTo("major", 123);

Query on String

Use whereStartsWith to restrict to string values that start with a particular string. Similar to a MySQL LIKE operator, this is indexed so it is efficient for large datasets:


// Finds beacon's name that start with 'Beacon'.
ApigoQuery query = ApigoQuery.getQuery("Beacon");
query.whereStartsWith("name", "Beacon"); 

The above example will match any ApigoObject where the value in the name String key starts with “Beacon”. For example, both “Beacon One” and “Beacon Two” will match, but “First Beacon” or “Second Beacon” will not.
Use whereEndsWith to restrict to string values that end with a particular string.


// Finds beacon's name that end with 'One'.
ApigoQuery query = ApigoQuery.getQuery("Beacon");
query.whereEndsWith("name", "One");

The above example will match any ApigoObject where the value in the name String key ends with “One”. For example, “Beacon One” will match, but “One Beacon” will not.

Counting Objects

If you just need to count how many datas match a query, but you do not need to retrieve all the datas that match, you can use count instead of find. For example, to count how many beacons have major greater than 123:


ApigoQuery query = ApigoQuery.getQuery("Beacon");
query.whereGreaterThan("major", 123);
query.countInBackground(new CountCallback() {
    @Override
    public void done(int count, ApigoException e) {
        if (e != null) {
            // exception happen, handle the message
            return;
        } 

        // counting succeeded, show beacons count
    }
});

User

Managing User

Apigo provide a specialized bucket User that automatically handles much of the functionality required for user management. With this bucket, you’ll be able to manage user account functionality in your app.

Signing Up

The first thing your app will do is probably ask the user to sign up. The following code illustrates a typical sign up:


// create new instance of User
ApigoUser user = new ApigoUser();

// set default field
user.setUsername("user.one");
user.setPassword("user1234");
user.setEmail("user.one@apigo.com");

// set custom field
user.put("dateOfBirth", new Date());
user.put("height", 177.5);
user.put("weight", 78);
user.put("isMarried", true);
user.put("myObject", new JSONObject());
user.put("myArray", new JSONArray());

// execute register user asynchronous
user.signUpInBackground(new SignUpCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // register succeeded
    }
}); 

This call will asynchronously create a new user in your Apigo App. Before it starts, the call will checks to make sure that the email are unique. Also, it also securely hashes the password in the cloud using bcrypt. We never store passwords in plaintext, nor transmit passwords back to the client in plaintext.

If a register isn’t successful, you should read the ApigoException that is returned. The most likely case is that the email has already been taken by another user. You should communicate this to your user clearly, and ask them to try a different email.

Logging In

After you allow users to sign up, you need be able to let them log in to their account in the future. To do this you can use several method for handling action in login process.

After you allow users to register, you need be able to let them login to their account in the future. To do this, you can use the class method logInInBackground.


ApigoUser.logInInBackground("myUsername", "myPlainPassword", new LogInCallback() {
    @Override
    public void done(ApigoUser user, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // log in succeeded
    }
});

Session

It would be bothersome if the user had to login every time they open your app. You can avoid this by using the cached currentUser object.

Whenever you use any signup or login methods, the user is cached on disk. You can treat this cache as a session, and automatically assume the user is logged in:


ApigoUser user = ApigoUser.getCurrentUser();
if (user != null) {
    // user logged in, open main activity
} else {
    // session not found, open login activity
}

Log Out

You can clear the current user by logging them out:


ApigoUser.logOutInBackground(new LogOutCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // log out succeeded
    }
});

Querying Data

To query for users, you need to use the special user query:


ApigoQuery query = ApigoUser.getQuery();
query.whereEqualTo("gender", "female");
query.findInBackground(new FindCallback() {
    public void done(List objects, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // query succeeded
    }
});

In addition, you can use get to get a ApigoUser by id.

Messaging Sender

Sender is number that plot by admin for sending message, you can't subscribe number that not in backend list. The number that allowed to subscribe are : FREENUM0, FREENUM1.

Properties
  • number -> String, used to store number object id.
  • price -> Number, used to store price of this number (readonly).
  • active -> Boolean, used to store status active this record (readonly).
Creating Sender

MessageSender sender = new MessageSender();
sender.setNumber("FREENUM1");
sender.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // sender saved, show success message
    }
});

Updating Sender

// saved sender
MessageSender sender;
// changing new number
sender.setNumber("FREENUM0");
sender.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // sender updated, show success message
    }
});

Deleting Sender

// saved sender
MessageSender sender;
sender.deleteInBackground(new DeleteCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // sender deleted, show success message
    }
});

Querying Sender

ApigoQuery query = ApigoQuery.getQuery(MessageSender.class);
query.findInBackground(new FindCallback() {
    @Override
    public void done(List list, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // show senders in a list
    }
});

Messaging Recipient

Messaging Recipient

Recipient is number that plot by user for receiving message. This module is used to send broadcast, with template, and broadcast with template.

Properties
  • number -> String, used to store number of recipient validate min.9 max.15 start with 62.
  • group -> String, used to store group name.
  • params -> Object, used to store params value of template validate json object string.
Creating Recipient

MessageRecipient recipient = new MessageRecipient();
recipient.setNumber("6281234567890");
recipient.setGroup("IT");

Map map = new HashMap<>();
map.put("kode", "901");
recipient.setParams(map);

recipient.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // recipient saved, show success message
    }
});

Updating Recipient

// saved sender
MessageRecipient recipient;
// changing data
recipient.setNumber("6281234234234");
recipient.setGroup("Staff");

Map map = new HashMap<>();
map.put("kode", "902");
recipient.setParams(map);

recipient.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // sender recipient, show success message
    }
});

Deleting Recipient

// saved recipient
MessageRecipient recipient;
recipient.deleteInBackground(new DeleteCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // recipient deleted, show success message
    }
});

Querying Recipient

Request:


ApigoQuery query = ApigoQuery.getQuery(MessageRecipient.class);
query.findInBackground(new FindCallback() {
    @Override
    public void done(List list, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // show recipients in a list
    }
});

Messaging Templates

Template is string content message that can possible to custom value by variable with prefix #. eg. Hi #name, please use this code #code to redeem point.

Properties
  • title -> String, used to store of title template.
  • content -> String, used to store template content.
  • approved -> Boolean, approved status of this template (readonly).
Creating Template

MessageTemplate template = new MessageTemplate();
template.setContent("Dapatkan diskon belanja s.d 50% dengan menukarkan kode #kode ini.");
template.setTitle("Promo Akhir Tahun");
template.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // template saved, show success message        
    }
});

Updating Templates

// saved template
MessageTemplate template;
template.setContent("Dapatkan diskon belanja s.d 70% dengan menukarkan kode kupon berikut #kode.");
template.setTitle("Promo Awal Tahun");
template.saveInBackground(new SaveCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // template saved, show success message        
    }
});

Deleting Templates

MessageTemplate template;
template.deleteInBackground(new DeleteCallback() {
    @Override
    public void done(ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // template deleted, show success message
    }
}); 

Querying Templates

ApigoQuery query = ApigoQuery.getQuery(MessageTemplate.class);
query.findInBackground(new FindCallback() {
    @Override
    public void done(List list, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // show templates in a list
    }
});

Messaging Log

Messaging Logs

History data of sending message (SMS, MMS, and USSD)is collected in this module. User can get all of this data or spesific by Message Type.

Properties

All fields are readonly.

  • transactionId -> String, unique id that recive from third party of telco.
  • sender -> String, sender of message.
  • recipient -> String, recipient of message.
  • content -> String, content of message.
  • msgType -> String, type of message : sms, mms, or ussd.
  • sendTime -> Date, time of sending message.
  • receiveTime -> Date, time of receiving message.
  • sandBox -> Bool, type of call this api (sandBox:true --> only save data).
  • status -> String, status of sending message : sending and sent.

Querying Logs

ApigoQuery query = ApigoQuery.getQuery(MessageLog.class);
query.findInBackground(new FindCallback() {
    @Override
    public void done(List list, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // show logs in a list
    }
});

Send Message

Send Message

This module is handling function for sending sms, mms, or ussd with 4 types sending method :

  • Direct -> This method used to sending direct message.
  • BroadCast -> This method used to sending broadcast message refer to group name in _MessageRecipient.
  • Template -> This method used to sending message with template refer to templateId in _MessageTemplate.
  • BroadCast with Template -> this method used to sending message refer to _MessageRecipient and _MessageTemplate.

Send Template

Properties

  • sender -> String, sender number, refer to data in MessageSender.
  • recipient -> String, recipient number.
  • templateId -> String, objectId, refer to data in MessageTemplate.
  • params -> String, json object string that replace template variable eg. {"kode":"918"}.
  • sandBox -> Boolean, default false, set true if you want to store data only.

Sending Message

Message message = new Message.BuilderDirectTemplate()
    .setSender(MessageSender.createWithoutData(MessageSender.class, "SENDER_ID"))
    .setRecipient(MessageRecipient.createWithoutData(MessageRecipient.class, "RECIPIENT_ID"))
    .setTemplate(MessageTemplate.createWithoutData(MessageTemplate.class, "TEMPLATE_ID"))
    .setSandbox(true)
    .setMessageType(MessageType.SMS)
    .build();
message.sendMessageInBackground(new SendMessageCallback() {
    @Override
    public void done(List logs, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // message sent, show success message
    }
});

Send Template BroadCast

Properties

  • sender -> String, sender number, refer to data in MessageSender.
  • group -> String, group name, refer to data in MessageRecipient.
  • templateId -> String, objectId, refer to data in MessageTemplate.
  • sandBox -> Boolean, default false, set true if you want to store data only.

Sending Message

Message message = new Message.BuilderBroadcastTemplate()
    .setSender(MessageSender.createWithoutData(MessageSender.class, "SENDER_ID"))
    .setTemplate(MessageTemplate.createWithoutData(MessageTemplate.class, "TEMPLATE_ID"))
    .setGroup("EyroDev")
    .setSandbox(true)
    .setMessageType(MessageType.SMS)
    .build();
message.sendMessageInBackground(new SendMessageCallback() {
    @Override
    public void done(List logs, ApigoException e) {
        // check if there is an exception happen
        if (e != null) {
            // handle the exception
            return;
        }

        // message sent, show success message
    }
});

MessagingError

Error Codes

The following is a list of all the error codes that can be returned by the Apigo API - Messaging.

Name Error Code Description
IllegalSenderNumber 1001 illegal sender number.
MissingSenderNumber 1002 missing sender number.
DontHaveActiveSenderList 1003 don't have any active sender list.
SenderAlreadyExist 1004 sender number already exist.
MissingRecipientNumber 1005 missing recipient number.
IllegalRecipientNumber 1006 illegal recipient number.
InvalidParamsFormat 1007 invalid params format.
ObjectParamsMustBeString 1008 object value params must be string.
MissingContentMessage 1009 missing message content.
OverLimitContent 1010 max length of body is 160.
MissingTemplateId 1011 missing templateId.
InvalidTemplateId 1012 invalid template id.
InactiveTemplate 1013 inactive template.
SensitiveWord 1014 message contain sensitive word.
IllegalNotifyUrl 1015 illegal notify url.
DontHaveActiveGroupList 1016 don't have any active group list.
MissingGroupName 1017 missing group name.
MissingMsgType 1018 missing message type.
InvalidMsgType 1019 invalid message type.
OtherCause -1 custom errors.