What is Parse SDK in Android

Parse is an open-source platform that provides one of the easiest ways to get a database and RESTful API up and running. If you want to build a mobile app and don't want to code the back-end by hand, give Parse a try.

Parse on Heroku

We can deploy our own Parse data store and push notifications systems to Heroku leveraging the server open-sourced by Parse. Parse is built on top of the MongoDB database which can be added to Heroku using MongoLab.

To get started setting up our own Parse backend, check out our configuring a Parse Server guide. Once the Parse server is configured, we can initialize Parse within our Android app pointing the client to our self-hosted URL. After that, the functions demonstrated in this guide work the same as they did before.

Alternatives to Parse

A comprehensive list of alternatives can be reviewed here. One of the primary alternatives is Google's Firebase, which provides a hosted solution for analytics, crash reporting, and a realtime JSON database. One major difference is that Parse still provides many powerful constructs for querying data, whereas Firebase requires you to perform this querying based on child/parent relations. See this guide for more information to porting Parse applications to Firebase.

What is Parse?

Parse is an open-source Android SDK and back-end solution that enables developers to build mobile apps with shared data quickly and without writing any back-end code or custom APIs.

Parse is a Node.js application which is deployed onto a host such as Heroku (or AWS) and then creates an automatic API for user authentication and storing data to a MongoDB document store. Parse has the following features included by combining the mobile SDK and back-end service:

  • User registration and authentication
  • Connecting user with Facebook to create a user account.
  • Creating, querying, modifying and deleting arbitrary data models
  • Makes sending push notifications easier
  • Uploading files to a server for access across clients

In short, Parse makes building mobile app ideas much easier!

Setup

Installing the Parse SDK

Setting up Parse starts with deploying your own Parse instance to Heroku or another app hosting provider.

Add this in your root file (not your module file):

Open the in your project and add the following dependencies:

Select to load the libraries through Gradle. When you sync, it will import everything automatically. You can see the imported files in the External Libraries folder.

Initializing the SDK

Next, we need to create an class and initialize Parse. Be sure to replace the initialization line below with your correct Parse keys:

The path needs to match the environment variable, which is set to this value by default.

We also need to make sure to set the application instance above as the for the application within the . This change in the manifest determines which application class is instantiated when the app is launched and also adding the application ID metadata tag:

Setup network permissions

We also need to add a few important network permissions to the :

Testing Parse Client

Assuming you have access to the Parse instance, you can test the SDK to verify that Parse is working with this application.

Let's add the test code to as follows:

Run your app and a new object of class will be sent to the Parse Cloud and saved. See browsing Parse data for more information about how to check this data.

If needed in your application, you might also want to setup push notifications through Parse as well at this time.

You should be setup now! Follow the remaining documentation guide to understand how to leverage Parse for your entire backend.

Working with Users

At the core of many apps, there is a notion of user accounts that lets users access their information in a secure manner. Parse has a specialized as a part of their SDK which handles this functionality. Be sure to check out the Users docs for a complete overview. See the API docs for ParseUser for more details.

User Signup

Creating a new user account is the process of constructing a object and calling :

This call will asynchronously create a new user in your Parse App. Before it does this, it checks to make sure that both the username and email are unique. See the signup up docs for more details.

User Session Login

We can allow a user to signin by calling and passing the user details:

If the credentials are correct, the will be passed back accordingly. You can now access the cached current user for your application at any time in order to determine the session status:

User Logout

A user can be signed back out with:

That's the basics of what you need to work with users. See more details by checking out the User official docs.

You can also have a Facebook Login or Twitter Login for your users easily following the guides linked.

Querying Users

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

See a list of query constraints here.

Working With Data Objects

Storing data on Parse is built around the . Each contains key-value pairs of JSON-compatible data. This data is schema-less, which means that you don't need to specify ahead of time what keys exist on each . Each has a class name that you can use to distinguish different sorts of data. See the API docs for ParseObject for more details.

Creating Parse Models

When using Parse, the best practice is to create models that represent our data and that subclass to allow for Parse persistence. Suppose we wanted to create a model:

We need to make sure to register this class with Parse before we call :

Now we can add fields and constructors to our :

Notice that now our model has , as well as property methods for storing which user created the TodoItem.

Note: When creating Parse models, avoid creating unnecessary member instance variables and instead rely directly on -type methods to retrieve the values of database properties.

Saving or Updating Objects

Let's suppose we wanted to save a to the Parse database, create a new , set the data attributes and then trigger a save with :

Note that there are two ways to save an object: which executes immediately and which will store the update on the device and push to the server once internet access is available.

See the saving objects and updating docs docs for more details. Also, check out the relational data section.

Querying Objects

Objects By Id

If you have the objectId, you can retrieve the whole using a :

See retrieving objects official docs for information on refreshing stale objects and more.

Objects By Query Conditions

The general pattern is to create a , put conditions on it, and then retrieve a of matching ParseObjects using the method with a . For example, to find all items created by a particular user:

See a list of query constraints here and check the queries overview for explanation of compound queries and relational queries.

Objects by Querying GeoLocation

Often we might want to query objects within a certain radius of a coordinate (for example to display them on a map). With Parse, querying by to retrieve objects within a certain distance of a location is built in. Check the AnyWall Tutorial and the whereWithinMiles and related conditions for more details.

If you want to query this based on a map, first you can add a listener for the map camera. Next, you can determine the visible bounds of the map as shown there. Check the Maps Usage Guide for additional information on using the map.

Live Queries

One of the newer features of Parse is that you can monitor for live changes made to objects in your database To get started, make sure you have defined the ParseObjects that you want in your NodeJS server. Make sure to define a list of all the objects by declaring it in the and :

See this guide for more details. Parse Live Queries rely on the websocket protocol, which creates a bidirectional channel between the client and server and periodically exchange ping/pong frames to validate the connection is still alive. Websocket URLs are usually prefixed with ws:// or wss:// (secure) URLs. Heroku instances already provide websocket support, but if you are deploying to a different server (Amazon), you may need to make sure that TCP port 80 or TCP port 443 are available.

You will need to also setup the client SDK by adding this dependency to your config:

where is the latest version

Next, instantiate the client:

Define the query pattern you wish to listen for events:

Create a subscription to this instance:

Finally, listen to the events. You can listen for , , , and . An enter and leave event reflects changes to an existing ParseObject that either now fulfill the criteria or no longer do so. See this guide for more information about the live queries protocol specification.

Passing Objects Between Activities

Often with Android development, you need to pass an object from one Activity to another. This is done using the system and passing objects as extras within a bundle. Unfortunately, does not currently implement Parcelable or Serializable.

The simplest way to pass data between activities in Parse is simply to pass the object ID into the Intent:

and then refetch the object using the object ID within the child Activity:

You can also use instead to retrieve the item in a synchronous style. Review the different caching policies to understand how to make this fast.

While we could implement parceling ourselves this is not ideal as it's pretty complex to manage the state of Parse objects.

Associations

Objects can have relationships with other objects. To model this behavior, any can be used as a value in other s. Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency.

One-to-One Relationships

For example, each Comment in a blogging app might correspond to one Post. To create a new Post with a single Comment, you could write:

By default, when fetching an object, related s are not fetched. We can preload (eagerly fetch these) by using the method on any :

We can eagerly load nested associations as well. If you have an objectA which has a column referencing objectB and then objectB has a column referencing objectC, you can get objectB and objectC by doing:

Otherwise, these associated objects can only be retrieved once they have been fetched separately:

Many-to-Many Relationships

You can also model a many-to-many relation using the object. This works similar to , except that you don't need to download all the s in a relation at once.

By default, the list of objects in this relation are not downloaded. You can get the list of Posts by calling findInBackground on the ParseQuery returned by getQuery. The code would look like:

For more details, check out the official Relational Data guide. For more complex many-to-many relationships, check out this official join tables guide when the many-to-many requires additional metadata.

Deleting Objects

To delete an object from the Parse Cloud:

Naturally we can also delete in an offline manner with:

Local Storage Mode

Parse now supports a more powerful form of local data storage out of the box which can be used to store and retrieve ParseObjects, even when the network is unavailable. To enable this functionality, simply call Parse.enableLocalDatastore() before your call to initialize:

Saving To Local Store

You can store a ParseObject in the local datastore by pinning it. Pinning a ParseObject is recursive, just like saving, so any objects that are pointed to by the one you are pinning will also be pinned:

Querying from Local Store

We can query from the local offline store with the flag during any query operation:

Further Details

For the full summary of how to utilize the offline mode for Parse, be sure to review the official local store guide in the Parse docs.

Using the Data Browser

Suppose we had a simple todo application with user accounts and items persisted to Parse. The next step is to setup and create our models using the Parse dashboard to manage your new app. Visit the "Data Browser" for the correct application and let's create our and objects for our app.

First, remove the test code that we added previously and drop the "TestObject" listed in the browser to clear testing data.

Next, select "New Class" and pick "User" to create the user object used to manage session authetication:

Let's also add our "Custom" class which can represent any custom data. In this case, we will create a class:

Now, we need to add our custom columns to our class. In this case, let's add a "body" field to our by selecting "+Col" and then selecting the type as a String and column name as "body":

Once you've finished adding your columns to the class, you can create as many additional classes as necessary and configure their respective columns. Let's add a row of data to the class directly through the data browser:

We are now ready to access these classes within our application.

Troubleshooting

Check out our Troubleshooting Common Issues with Parse guide for a detailed look at common issues encountered and related solutions.

Additional Features

Parse has many powerful features in addition to the core functionality listed above.

Uploading Photos

Parse has full support for storing images and files uploaded by an application. Photos are stored using the construct described in more detail here.

First, make sure to create a Parse model. Next, you will need to add a object:

A instance can be initialized with a object or a byte array. Follow the CodePath Camera and Gallery Guide guide for capturing photos with a camera.

Rendering ParseFile objects

To render a ParseFile in an ImageView, you can use Parse's UI Widget library and use the , which provides helper methods to load the image asynchronously. First, you need to add the Parse UI Widget to your declaration:

Instead of an , use the class:

To load the , use the method and call :

Alternatively, if you have a third-party library such as Glide or Picasso, you can also reference the URL directly and don't need to use this special widget.

Geo Location

Parse has support for geolocation services and querying:

  • AnyWall Sample App - Sample app including how to read geolocation and use this data within your app.

Push Notifications

Parse supports push notifications made easy:

Facebook SDK

For a quick way of incorporating Facebook login, check out Parse's UI Library. It leverages Parse's FacebookUtils library, which acts as a wrapper for associating objects with Facebook users.

The official step by step instructions for integrating Parse with Facebook SDK is located here. The manual process of integrating with Facebook's SDK is discussed below.

You will first need to create a Facebook app and get an Application ID. If you are using open source Parse, make sure to set the environment variable too.

You will also need to get access to your keystore hash and make sure to include it:

OS X:

Windows:

Next, you will need to include Parse's FacebookUtils library, which provides an easy-to-use wrapper to work with the Facebook SDK, as well as Facebook's SDK:

where is the latest version:

You will then need to make sure to initialize these libraries by doing so in your file:

Note that you need to add /parse in the url in order for Parse to work, not just the hostname.

Make sure to reference this in your file:

Make sure to add the to your manifest file, as well as the application ID and permissions you wish to request.

There are two ways to support Facebook login: one is to use your own custom button/icon, or to use Facebook's class as described in the walkthrough. If you choose to use the class, you should not use the library to trigger a login. The reason is that Facebook's already has click handlers that will launch a login screen, so using Parse's code triggers two of these screens to appear. In addition, you have to do more work to associate a object with a Facebook user. For this reason, it is simpler to use the custom button approach when integrating with Parse.

Custom button

For your , add this code to trigger a login. If you wish to trigger this login, you may add your own custom button:

You can then attach a button click handler.