Requirements

Prerequisite knowledge
Familiarity with PhoneGap
 
Required products
 
Sample files
 
User level
Intermediate
 
The PhoneGap platform enables web developers of all backgrounds to break into mobile development. PhoneGap facilitates the transition from web to native applications (while also providing access to device features like the camera, microphone, and accelerometer), but there are still things a developer has to build themselves. One of the primary areas of concern for a mobile app is data storage.
 
Adding data storage to mobile apps
 
When you build applications that allow end users to store content, you must find a solution to store that data in a persistent manner. You have a few options:
  1. You can store all the data locally on the device itself. PhoneGap provides access to a client-only database solution via its Database API. This works well, especially with developers used to working with SQL databases. But the data is confined to the device. If the user installs your application on another device (such as a tablet), then they can't access the same data.
  2. You can store data on a remote server. It’s easy to set up AJAX to connect to a remote server in order to send and retrieve data. But this requires setting up a server, installing some form of middleware (ColdFusion, PHP, Node, or others) and setting up an API on the server to handle authentication, data creation, queries, and more. If you choose this option, you are responsible for server maintenance. You might as well go out and have a kid, adopt a dog, and promise to water your neighbor’s plants while you’re at it.
  3. You can offload the maintenance of the server, the creation of an API, the storage requirements, and essentially delegate all tasks related to storing data to a third-party solution. All of this is available if you use the Parse mobile application platform.
Parse allows clients to store data on their servers. The stored data can be of any form. Want to build a blog platform? You can store blog entries. Want to build a forum? You can store forum posts. Want to design a shopping network catering specifically to the needs of zombies? Parse makes it easy.
Parse pricing is structured in three plans. The lowest plan, Basic, is 100% free and provides significant capabilities as part of the free service. You can sign up as a developer for free, too. If you evaluate Parse and decide it’s not for you, Parse includes the ability to export your data. You aren't stuck using Parse if you decide to use a different strategy. Parse is a casual affair that can quickly grow into love for many developers.
Parse offers several different ways to use their service. You can use a set of APIs that are written as native libraries. While PhoneGap developers typically avoid working in the native language of each platform, those who wish to create their applications using native technologies can take advantage of full featured SDKs for their target platforms. (At the time of this writing, SDKs for Android, iOS, and Windows are available.)
You can also use a simple REST-based API. While you can use this from PhoneGap, this is typically used for server-side development. One of the benefits of Parse is the ability to completely skip working with a server, but you may still wish to use a traditional web server. With the REST API, your server can communicate to Parse to fetch and work with data.
And finally, you can use the JavaScript API. This allows JavaScript developers to make full use of the Parse API from PhoneGap or web applications. In the next section, you'll learn how to use the JavaScript API and see how to add Parse to your application.
 
Working with Parse

 

To begin, register for Parse on their website.
  1. Visit parse.com and create a free account.
After signing up, Parse displays the Get Started form to build a new application (see Figure 1).
Figure 1. Enter the details of the application in the Get Started form.
Enter the app name of your choice. For the purposes of this article, the app name is: ADCApp.
After completing the registration process, a Welcome page appears.
  1. Click the Dashboard link (in the top menu or in the Welcome page).
This dashboard provides many features. For now, you'll focus on the features related to data browsing and settings.
  1. Review the options in the Information tab on the left side (see Figure 2).
Figure 2. The Information tab contains settings for the application.
This Information tab contains various keys for integrating with the JavaScript API. For this example, you only need the Application ID and JavaScript Key. Later, when you edit the code, you'll copy these values.
  1. Click the Downloads link at the top of the page.
The JavaScript section includes several links, including a minified version of the SDK.
  1. Download the SDK and place it to a new folder.
  2. Download the sample files provided above to obtain the code for this application and place the files in the new folder as well.
Before we go any further, we should decide what we want to build. Parse allows us to store data of any form at all. To keep things simple for our sample application, we will design a note application. The application enables you to write new notes as well as see your previously created notes.
 
Creating a simple note application

 

To make things as simple as possible, the app doesn't use a particular UI framework. This isn't the most elegant way to develop the application, but its primary focus is to illustrate how to work with the Parse API.
  1. Launch the HTML editor of your choice, and create an HTML file in the local root folder of a site project.
  2. Copy the code below, paste it into the HTML page, and save it.
<!doctype html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="jquery.min.js"></script> <script src="parse.min.js"></script> <script src="main.js"></script> </head> <body> <h2>Note Application</h2> <div id="notes"></div> <form id="addNote"> <p> <input type="text" id="noteTitle" placeHolder="Note Title"> </p> <p> <textarea id="noteBody" placeHolder="Enter note text here."></textarea> </p> <p> <input type="submit" id="addNoteBtn" value="Add Note"> </p> </form> </body> </html>

 

Note: The code above references parse.min.js. The copy of the file you may have downloaded from Parse.com includes its version, for example: parse-1.1.12.min.js. As you follow along, you can rename it or simply edit the sample code to match.
This simple application loads jQuery, the Parse SDK, and a file called main.js. The HTML consists of an empty div tag and a form. The empty div tag contains the content that loads from Parse, which will come into use after posting some text content. The form in the app enables users to enter new content. In this case, the form contains two fields to enter the note's title and the note's body text. Remember, Parse allows you to save anything. If your concept of a note includes a field related to indicating the happiness level of the note - just add it.
  1. Take a moment to review to main.js, which contains most of the application logic.
//Parse related keys var PARSE_APP = "[Parse.com Application ID]"; var PARSE_JS = "[Parse.com JavaScript Key]"; $(document).ready(function() { Parse.initialize(PARSE_APP, PARSE_JS); NoteObject = Parse.Object.extend("NoteObject"); $("#addNoteBtn").on("touchend", function(e) { e.preventDefault(); //Grab the note details, no real validation for now var title = $("#noteTitle").val(); var body = $("#noteBody").val(); var note = new NoteObject(); note.save({title:title, body:body}, { success:function(object) { console.log("Saved the object!"); }, error:function(object,error) { console.dir(error); alert("Sorry, I couldn't save it."); } }); }); });
  1. Edit the code, replacing the PARSE_APP and PARSE_JS variables with the Application ID and JavaScript Key from the Parse dashboard.
You can use the jQuery document.ready() function to run some code when the page is done loading. Before we can use Parse, you must first initialize it. It is a simple call that makes use of the variables created earlier.
The next line is important:
NoteObject = Parse.Object.extend("NoteObject");
When you decide which type of data you want to create, you must name it. In the provided code, it is named NoteObject. Once the Parse object is named, you can ask the Parse SDK to create an object type by extending the core Object class. The end result is a NoteObject that acts like a new class.
As you read through the code, you'll see the simple logic tied to the form. When the button is tapped, the code captures the text content values entered in the form fields.
Note: To test touch events on a desktop browser, you can either temporarily change the code to click, or use Chrome Dev Tools to enable touch emulation. To use Chrome Dev Tools, update the options by clicking the settings icon in the lower right corner of the Dev Tools dialog box, and then select the Overrides tab. Scroll down and enable the Emulate Touch Events option.
Next, you'll make a new instance of NoteObject and run the save method on it. The save method’s first argument is the data itself. In this example, there is a key named title and a key named body. These two keys represent the input fields of the NoteObject. However, you can use any names you prefer, because Parse is flexible. When necessary, you can even change the key names later (although it is a best practice to keep the names as consistent as possible.)
The next argument is a generic JavaScript object that contains a success and error
key. These are both functions and represent the logic that is called based on the result of the save operation. In the case of an error, an alert is displayed to the user. When the note content is successfully saved, the code outputs a success message to the JavaScript console. You can improve these behaviors later.
 
Testing the application
After editing the sample application, it's time to test it.
  • Open the HTML file in your browser. Enter some text content in the fields and click Save.
If your browser’s JavaScript console is open, you can see the result.
  • To confirm that the text content was successfully saved to the Parse framework, visit the Parse dashboard, click the Data Browser tab, and you'll see the saved text content (see Figure 3).
Figure 3. The text submitted in the form fields is listed in the Data Browser tab.
Notice that the Data Browser list includes additional properties that were saved with the data. Parse captures useful data regarding related fields, such as createdAt and updatedAt time stamps. Also note that an objectId was automatically assigned to the stored data.
Your HTML application just created content and stored it, for free and without a server (well, without requiring you to set up a server.)
 
Displaying stored data from Parse
 
Next, you'll see how to list objects. Review the following updated version of main.js that lists stored note content when the application loads.
 

//Parse related keys
var PARSE_APP = "[Parse.com Application ID]";
var PARSE_JS = "[Parse.com JavaScript Key]";

$(document).ready(function() {
Parse.initialize(PARSE_APP, PARSE_JS);

NoteObject = Parse.Object.extend("NoteObject");

function getNotes() {
var query = new Parse.Query(NoteObject);

query.find({
success:function(results) {
console.dir(results);
var s = "";
for(var i=0, len=results.length; i<len; i++) {
var note = results[i];
s += "";
s += ""+note.get("title")+"";
s += "Written "+note.createdAt + "";
s += note.get("body");
s += "";
}
$("#notes").html(s);
},
error:function(error) {
alert("Error when getting notes!");
}
});
}

$("#addNoteBtn").on("touchend", function(e) {
e.preventDefault();

//Grab the note details, no real validation for now
var title = $("#noteTitle").val();
var body = $("#noteBody").val();

var note = new NoteObject();
note.save({title:title, body:body}, {
success:function(object) {
console.log("Saved the object!");
$("#noteTitle").val("");
$("#noteBody").val("");
getNotes();
},
error:function(object,error) {
console.dir(error);
alert("Sorry, I couldn't save it.");
}
});
});

//call getNotes immediately
getNotes();

});

In this section, you'll focus on updating the application file.
  • Review the getNotes function that begins by creating an instance of a Parse.Query object.

function getNotes() {
var query = new Parse.Query(NoteObject);

query.find({
success:function(results) {
console.dir(results);
var s = "";
for(var i=0, len=results.length; i<len; i++) {
var note = results[i];
s += "";
s += ""+note.get("title")+"";
s += "Written "+note.createdAt + "";
s += note.get("body");
s += "";
}
$("#notes").html(s);
},
error:function(error) {
alert("Error when getting notes!");
}
});
}

The code above illustrates how you can query data from Parse. The NoteObject
class is passed in, so the query works only with that particular class. When you run the find method on this object, the results are returned in a simple array. Using a loop over the array, you can generate HTML to display the data in the DOM.
Notice that the title and body attributes are retrieved using a get() API, while the default properties created by Parse exist on the object itself. (In the example above, this is the createdAt property.) Here’s an example of how the list displays in Chrome (see Figure 4).
Figure 4. The data stored in Parse is displayed in the application.
The note add handler is also updated to clear the form out and call the getNotes function again. That is not the most elegant approach, but it works. Parse has an incredibly powerful Query API that allows for any number of filtering options. If you want to make this application a bit more performant, you can modify the code to get results for objects created after a timestamp, based on when the form was submitted.
Suggestions for extending the application
This article just scratches the surface of what you can achieve using Parse. To get more information, read the JavaScript Guide. Some features of particular interest are:
  • User handling: This includes user management logic that is otherwise difficult to set up. For example, you can ensure email addresses are not duplicated, manage reset passwords, and cache login credentials for automatic login functionality.
  • Full security: In this sample project, all objects are returned to the mobile device. But in a real world application, notes would be associated with their creators. Parse has a robust user model, with support for associating objects with users. You can also create groups and set other permissions on objects as you see fit.
  • Twitter and Facebook integration: I’ve never heard of these sites, but in case you have, Parse helps you integrate with them.
  • Geolocation: While Parse doesn’t add geolocation support per se, it does include a special way of handling objects that have GPS data. So if your application can access the user’s location, you can simply store that data along with the object. You can then use the Query API to look for data near a location. This functionality is extremely handy for location-based applications.
 
Where to go from here
In this article, you learned how to use Parse to store data in mobile applications. You may be wondering how PhoneGap fits into this workflow. PhoneGap offers the opportunity to leverage JavaScript libraries and APIs and bring them into the mobile space. All of the information provided above about Parse just works with PhoneGap. You can use the code from this article, upload it to a PhoneGap Build, and create a mobile application in about a minute.

 

 
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

More Like This