Building HTML5 Mobile App With StackMob API


In this tutorial we are going to create a mobile app connected to StackMob back end. The app will consist of two pages. On the first page we will display a list of messages retrieved from StackMob cloud-based database. We can also add a new message. Clicking on a message will take us to details page where the current message can be deleted. The two screens are shown below: 


Getting StackMob account

Signing up and creating new schema

Before we start building the app, we need to get a StackMob account. StackMob provides a free account so you can quickly sign up. 
  1. Once you signed up and signed in, click on Dashboard tab. We are going to create a new app. 
  2. On the right hand side, click to create a new app
  3. Enter app name and select app category:


  4. Click Create Application
  5. You should see the following menu on the right hand side, click Manage Schema - to create a new cloud-based table for our messages. 


  6. Click New Schema button (upper right corner)
  7. For Schema Name enter: messages
  8. Then click Add Field button
  9. For Field name enter: text and click Add Field
  10. Then Click Save Schema
  11. If you click back on Manage Schema and then on messages, you should see the following page:

Let's now enter some data into our table. 

Entering sample data

  1. Click Object Browser
  2. Select messages scheme (if not selected)
  3. Click Add Object
  4. Enter any string value for text, you don't need to enter anything for message_id, it will be automatically generated. 
  5. Enter a couple of more objects. The result should look something like this, after entering: Hello, World, Mobile


Now that we have some sample data, we can start building the mobile app. If you want to try querying the data, go to Test Console link. Then select messages under Crud Methods. We'll come back to this feature a little bit later. 

Creating a new mobile app

Let's start by creating a new app in Tiggzi app builder. 
  1. From Apps tab, click Start Now button
  2. Enter StackMobApp for app name and click Create. 
  3. A new app will be created, and the mobile editor will be loaded. 

Creating Messages page

  1. The new app already has one page, let's rename the page to Messages. Click the page and change its name in Properties. 
  2. Build the following UI by dragging and dropping components from the palette. The list component will display all messages currently saved in StackMob back-end and we can also add new messages. 


    1. New Message inside the input is HTML5 placeholder (set it via Properties)
    2. Button has an icon on the right side
    3. List - the number of items was reduced to 1 from 3, and Label component component was inserted instead of the default text. 
    4. The theme/Swatch used is: Dendrite/C (Gold)
  3. You can quickly test this page in browser (desktop) or the actual mobile device. Click the Test button to open the page in browser. 
    1. To test the app on mobile device, simple make the app link public and open the URL on your device. You may also scan the top QR code to open the URL. 
  4. There is just one more thing we want to do. Select the label component and change its name in properties to messageText. 

Creating a service to get all messages (GetMessages)

Let's start with our first service which will connect to StackMob and get all current messages. Before we do, let's see how we can do that using StackMob test console. 
  1. Click Test Console in StackMob dashboard
  2. Under Crud Methods, select messages
  3. In the middle of the screen you should see an option to select HTTP Verb:


  4. We want to try GET, so just click Submit. You should see request information request and response. The actual JSON response should look like this (depending on values you entered as sample data):


  5. If you look at the very beginning, you will see he service URL and authorization header. That's the URL we want to use when defining a service. 

    URL: http://api.mob1.stackmob.com/messages

    Authorization: OAuth realm="", oauth_signature="V9hEjbu1QkLtMD3jTnPgEaUNMpI%3D", oauth_nonce="47257743138944558", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="c7b6d223-af87-47b3-b080-51f9dbf47669", oauth_timestamp="1334268662"

We are now ready to create the actual service. 
  1. Go to Projects view, select Create New... > Service.
  2. For service name enter: GetMessages, click OK
  3. For URL, copy the URL above (URL: http://api.mob1.stackmob.com/messages) and paste it. 
  4. Check Use Tiggzi Proxy (here is why). Here is how it should look:


  5. Open Request Parameters panel, we are now going to define service request parameters. 
  6. Create the following two parameters (enter name, then click Add):
    1. Accept
      1. Set value to:  application/vnd.stackmob+json; version=0
    2. Authorization
  7. Mark both as Header. Here is how it should look:



    Note: Usually once we define service request parameters, we can test the service by clicking the Test Connection button. As this service requires calculating Authorization header using JavaScript, we can test it right now. A very nice feature when testing the service is that we can create the service JSON response structure automatically. Luckily, we can still create the response structure automatically even without running the service. 

  8. Open Response Parameters panel. 
  9. Click Populate from Sample Response - here we can paste sample JSON and automatically create the response 
  10. Go back to StackMob dashboard, to the result from GET request we did and copy the response. Then, paste the response:


  11. Click Populate Response Parameters, then Close. 
  12. You should now see the response created: 


We are done with this service. Before we add it to the page, let's take a short detour and create the JavaScript function to calculate the Authorization header .

Creating a JavaScript file

Creating a new JavaScript file is very simple
  1. In Projects view, click Create New... > JavaScript
  2. Change the name to Login and click OK. 
  3. Then, copy and paste the following code:
function getAuth(requestMethod, url){ 
   
    if (url == null) {
       url = 'http://api.mob1.stackmob.com/messages';
    }

    var key = 'paste_your_key';  
    var secret = 'paste_your_key';

   
var accessor = { consumerSecret: secret,  tokenSecret: "" };
    
    var message = { method: requestMethod, action: url, parameters:OAuth.decodeForm("") };
    
    message.parameters.push(['oauth_timestamp', OAuth.timestamp()]);
    message.parameters.push(['oauth_nonce', OAuth.nonce(17)]);
    message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
    message.parameters.push(['oauth_consumer_key', key]);
       
    OAuth.SignatureMethod.sign(message, accessor);
    var auth = OAuth.getAuthorizationHeader("", message.parameters);
    return auth;
}

This code basically creates the following header parameters by using oAuth version 1: 

Authorization: OAuth realm="", oauth_signature="V9hEjbu1QkLtMD3jTnPgEaUNMpI%3D", oauth_nonce="47257743138944558", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="c7b6d223-af87-47b3-b080-51f9dbf47669", oauth_timestamp="1334268662"

One more thing we need to do is insert app keys (right after the if statement). 
  1. In StackMob dashboard, under App Settings, click Manage App Info. You will see Public and Secret Key values. 
    1. key - paste Public Key value
    2. secret - paste Secret Key value
We need the if-statement because the service URL will be a little bit different when we will delete messages (we wll be adding message id). 

That's it. Click Save and then Close.  

Binding GetMessages service to the page

Let's add the service and bind it to the page. 
  1. From Projects > Services, select GetMessages service and drag and drop it over the page. 
  2. You will see a box on the left hand side showing the service instance was added. Click the label and change its name to: GetMsg


  3. To bind or map service to UI, click on Data Mapping tab. The editor will open with Request Mapping shown. We got the service on the left hand side and the page on the right hand side. To display a list of messages, we don't need any input from the page but we do need to set the Authorization header. 



  4. Click Add... in JavaScript column for Authorization parameter. 
  5. A JavaScript editor will open. We want to invoke the function we defined in previous step. Type the following: 

    return getAuth('GET');

    We want to get authorization for doing a GET request. 
  6. Click OK to close. 
  7. Let's now switch to Response Mapping. This is where we want to map service result to the page. 
  8. Create the following mappings:


    $ - is the collection of all messages, we map it to the list
    text - is the actual message, we map it to label inside the list
We are almost one. We just need to invoke the service. 

Invoking GetMessages service

We would like to load the users on page load. 
  1. Click outside the phone frame, open Events view.
  2. Add Event > Load
  3. Add Action > Invoke Service, select GetMsg service instance. Click OK. 
  4. Go ahead and test the app, you should see the messages you inserted at the very beginning. 
Go ahead and test the app on your device. 

Now that we got this working, let's create a service which will add a new message. 

Creating a service to add new message (AddMessage)

Before we start, you can to StackMob's Test Console and add a new message from there:


You don't need to enter message_id, it will be automatically created. The response should look like this: 

{
  "messages_id": "0c3cea54747f430eb2342f793ce461e4",
  "text": "New message!",
  "createddate": 1334274738762,
  "lastmoddate": 1334274738762  
}
  1. Project > Create New... > Service
  2. Name the service: AddMessage
  3. For service URL enter: http://api.mob1.stackmob.com/messages
  4. For Method select: post
  5. Check Use Tiggzi Proxy. 
  6. Open Request Parameters panel and add three parameters:
    1. Accept
      1. Set value to:  application/vnd.stackmob+json; version=0
      2. Mark as Header
    2. Authorization
      1. Mark as Header
    3. text (this will be the actual new message)
  7. Open Response Parameters panel and create the response the same way we did with the first service. Copy and then paste sample JSON response. You can also just copy the code above. 

Binding AddMessage service to the page

Let's first add the service to the page
  1. Drag and drop the service on to the page
  2. The service instance will appear on the left hands side. Change the service instance name to AddMsg:


  3. Open Data Mapping view
  4. We need to set Authorization header as before. Click Add.. and type the following: 

    return getAuth('POST');

  5. Then, we need to map the text input to input element on the page:


For the purpose of this example, we don't need to map the response. 

Invoking AddMessage service

We would like to invoke the service on button click. 
  1. Select the button, open Events view
  2. Add Event > Click
  3. Add Action > Invoke Service, select AddMsg service instance. Click OK. 
Once we add a new message, we also want to refresh the current list of messages. But we only want to refresh the list if AddMessage service finished successfully.
  1. Select AddMessage service, open Events tab
  2. Add Event > Success
  3. Add Action > Invoke Service, select GetMsg service instance. Click OK. 
We are ready to test the new functionality. Click the Test button to launch the app. 

Creating Delete page

Let's now work on the second page. 
  1. Create a new page and call it Delete. 
  2. Build the following UI:


    1. Rename the label to messageText
    2. The two buttons are places inside a grid, with two columns. 
    3. If you want to test just this page, go to Project > Project Profile, and set this to be the first page (just for testing, don't forget to set it back to Messages page when done). 

Preparing for creating delete service and page

Before we move on to creating the delete service, we'll need to add additional information to the Messages pages. More specifically, we want to click on a message and navigate to the page we just created. On that page we can delete the message. In order to know on which message we clicked, we need to add the message id to the list. We don't actually want to display it, so we are going to add but make it hidden. 
  1. Drag and drop another Label component inside the list. 
  2. Name the component messageId and uncheck Visible in properties


Next we need to update GetMessages service output mapping. 
  1. Select GetMsg service instance on the page, open Data Mapping and switch to Response Mapping
  2. Map messsage_id from the service to messageId element in the page:


Next, let's add navigation. When we click on a message, it will take us to the Delete page. But first, we also want to save the message text and id into local storage, so we will have access to them on the Delete page. 
  1. Select the list and open Events view
  2. Select Add Event > Click
  3. Select Add Action > Set Local Storage variable. Enter the values as shown



  4. Repeat the same for message id. Under Click event, select Add Action > Set Local Storage Variable. Enter the value as shown:


  5. Click OK. 
  6. Let's now add navigation. Under Click event, select Add Action > Navigate to Page. 
  7. Select Delete and click OK
There are should be three actions under Click event. Two to set a local storage variable and one to navigate. 

Displaying message text on Delete page

Now that we have stored the message text in local storage, let's read the message and display on a page. 
  1. Select the page (click outside the phone frame) and open Events tab
  2. Select Add Event > Load
  3. Select Add Action > Set Property and set the following values:

    Note: the label in your app might be mobilelableX (X is some other number). You can always rename the component. 

  4. Click OK. 
You can go ahead and test the app. Click on any message and the message should be displayed on the second page:

Creating Delete service

  1. In Project view, select Create New... > Service. Name the service DeleteMessage
  2. Set service URL to: http://api.mob1.stackmob.com/messages/{message_id}
    • message_id will be substituted when the service is running. 
  3. Change Method to delete
  4. Check Use Tiggzi Proxy
  5. Open Request Parameters panel and add three parameters:
    1. Accept
      1. Set value to:  application/vnd.stackmob+json; version=0
      2. Mark as Header
    2. Authorization
      1. Mark as Header
    3. message_id (this will be the id of the message we are deleting)
  6. Save. We don't get anything back from the service, so we don't need to define the response

Adding and binding Delete service to the page

  1. Open Delete page
  2. From Projects > Services, drag and drop Delete service into the page
  3. When service instance has been added, click on name and change it to DeleteMsg
  4. Open Data Mapping and create the following mappings:


    • Note that message_id from local storage is mapped to both Authorization header and message_id

  5. For Authorization parameter, click Add JavaScript and enter the following: 

    return getAuth('DELETE', 'http://api.mob1.stackmob.com/messages/'+value);

    For deleting, we need to add the message id to the URL for authentication.
Just one more thing we need to do and that's to invoke the service and add navigation. 

Invoking Delete service

  1. Select the Delete button
  2. Add Event > Click, then Add Action > Invoke Server, select the DeleteMsg service instance. 
  3. We want to navigate back to the first page only if the service completes. Select service instance. 
  4. In Events tab, Add Event > Succes, then Add Action > Navigate to Page, select Messages page. 
  5. Check Use full screen refresh:

     
  6. Select Cancel button, add navigation to back to Messages page (without full page refresh)
You are done! Go and test your app. 

What's next? 

  1. Try other Tiggzi tutorials
  2. StackMob has very rich API. Now that you know how to connect to StackMob you can easily use other services. 
  3. Learn how to test your app
  4. Learn how to export your app
  5. Learn more about creating and using services

Comments