Tag Archives

14 Articles

IoT Series: Real-Time Events on Parse Using Android




In our previous tutorials on IoT, we covered how to setup a Raspberry Pi and how to connect it to Parse Server using Back4App API to save objects to the server and to perform Queries and Live Queries.

Now we cover how to reproduce everything done on the Raspberry side to the App side. In this tutorial, we describe an Android App to interact with the IoT device configured earlier. From the Parse Server side, the App does the same tasks as the Raspberry: writes objects and performs Queries and Live Queries. Please note these functionalities may be useful even if you do not plan to develop an IoT application!

We provide our codes as a first step for you to develop your desired Apps.


The only prerequisite is to complete our Android QuickStart tutorial. For that, you need to click on the link mentioned below.


Here is a tutorial on LiveQuery which will be required on section 3 of this IoT Series tutorial. You do not have to complete it beforehand, though.


If you have any questions throughout the tutorial, you may get them resolved by following the official Parse guide for Android in the link below.


Section 1: Basics of creating your App and connecting with Back4App

In this project, we name our class as “MainActivity.java”. Here is the basic code that will help you get started.

public class MainActivity extends AppCompatActivity {

   protected void onCreate(Bundle savedInstanceState) {

      // Insert toolbar on app. Further description of this bar ins on menu_main_activity.xml file
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main_activity, menu);
      return true;

   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();

      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;

      return super.onOptionsItemSelected(item);

You may need to add the following imports:

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ToggleButton;
import android.view.View.OnClickListener;

On your layout XML file, make sure you add the following code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"

   <include layout="@layout/content_main_activity" />


          app:popupTheme="@style/AppTheme.PopupOverlay" />



To connect your app to Back4App, add the following code below within the onCreate() function of your class.

// Initializing Parse Server
Parse.initialize(new Parse.Configuration.Builder(this)
    .applicationId("YOUR_APP_ID") // from Core Settings, on "Features"
    .clientKey("YOUR_CLIENT_KEY") // from Core Settings, on "Features"

Remember to follow the step-by-step instructions on QuickStart to grant Internet Access to your app.

Section 2: Saving and Retrieving Objects on Parse and Displaying on App

Start by adding the imports below

import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;

In this section, we save objects of “CommandGPIO1” class with a button click. Every Parse Object has three default attributes: objectId, createdAt, and updatedAt. Our class will have two more additional attributes: content and destination. The values for content will be either “on” or “off”, and represent a status to be sent to a LED. For destination, all objects will contain “command”, but we could define different strings for different LEDs.

For example:

We create two buttons, and each of them writes a different value on content. To create a button, to add the following code to your layout XML file:

   android:text="Send ON"/>

In your class file, creating the button is as easy as writing:

Button buttonOn = (Button) findViewById(R.id.buttonSendOn);

If you are a beginner to Android programming, please note that the “findViewById” argument contains “buttonSendOn”, and this is the Android:Id we defined on the XML.

We want this button to save an object on Parse Server when it is clicked. To do so, add the following code:

buttonOn.setOnClickListener( new OnClickListener(){
   public void onClick(final View view) {

      // Creating new object and assigning proper attributes
      ParseObject command = new ParseObject("CommandGPIO1");

      command.put("destination", "command");
      command.saveInBackground(new SaveCallback(){
      public void done(ParseException e){
         Snackbar.make(view, "Sent ON to Output", Snackbar.LENGTH_LONG )
         .setAction("Action", null).show();

Note, we can add whatever function we want performed within the onClick callback function. Here, we create a “CommandGPIO1” class object, set content as “on”, and destination as “command”.

It is useful to know that we DO NOT have to define this class beforehand on the Parse dashboard! If you later choose to add a new attribute, or change the name of your class, then you just need to work on your code, and the changes will be automatically updated on the dashboard.

At this point, you should better test your app and check if the object is being created!



The SaveCallback shows a snackbar, which is a lightweight feedback on the bottom of your screen, as shown in the figure above.

Copy this code to create a button that writes objects with “off”. Change the following lines on the layout XML

android:text="Send OFF"/>

Create a new button and change the line where the content is being written:

Button buttonOff = (Button) findViewById(R.id.buttonSendOff);

Now that things are working properly on Parse Server, we want to provide a permanent feedback to the app user.  For that, we will use the EditText element, as shown below.

Define this element on the layout XML:

    android:maxLines ="2"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Within the onCreate() scope of your class, add the following code:

// Defining text element for showing status of output pin, which receives commands from the app
// The commands are sent by buttons, which are later described on this code.
final EditText textOutPin = (EditText) findViewById(R.id.status1Text);
textOutPin.setText("Loading status of output pin...");

The first line creates the object. The second line makes it non-editable for users. The third line makes it clickable, so it can be copied and pasted. The fourth line sets the initial text.

We want to write the content field of the last “CommandGPIO1” object saved on Parse onto this EditText object. Although we could do this using some logic within the code, we will actually retrieve objects from Parse by performing a ParseQuery since this provides more realistic and robust results.

The code below declares, sets parameters, and prints the results of a Parse Query.

ParseQuery<ParseObject> queryOut = ParseQuery.getQuery("CommandGPIO1");
queryOut.whereEqualTo("destination", "command");

queryOut.findInBackground(new FindCallback<ParseObject>() {
   public void done(List<ParseObject> objects, ParseException e) {
      if (e == null){
         textOutPin.setText("Output is " + objects.get(0).getString("content"));
         textOutPin.setText("Error: " + e.getMessage());

The first line creates the query. The second adds a constraint to select only those objects whose destination field contains “command”. The third line the objects starting with the newest ones. The fourth line limits the results to one, assuring we will retrieve the newest object.

The fifth line actives the query, and calls the callback function when it is finished. Here, we write the content of the retrieved object onto the previously defined EditText object.

We will add that piece of code right after declaring the EditText object, so a query is performed when the app is open, and also in the SaveCallback when saving a new object on Parse, to update the text automatically when creating new objects.

At this point, your app should work as illustrated in the following screen captures.

screenshot_1506531209    screenshot_1506531359

Finally, we add a refresh button to allow the users to perform the query above whenever they want. It will be done with a different style of button, i.e., a Floating Action Button.

Add this code onto the layout XML file:

    app:srcCompat="@android:drawable/ic_popup_sync" />

Now, within the onCreate() scope in the class, add the following code:

// Refresh button to obtain the output status when requested.
// The same query as the first is performed here
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener(){
    public void onClick(final View view){
        ParseQuery<ParseObject> queryOut = ParseQuery.getQuery("CommandGPIO1");
        queryOut.whereEqualTo("destination", "command");
        queryOut.findInBackground(new FindCallback<ParseObject>() {
            public void done(List<ParseObject> objects, ParseException e) {
               if (e == null){
                   textOutPin.setText("Output is " + objects.get(0).getString("content"));
                   textOutPin.setText("Error: " + e.getMessage());
               Snackbar.make(view, "Updated status of Output", Snackbar.LENGTH_LONG ).setAction("Action", null).show();

At this point we can now save objects on Parse Server, retrieve information from them and display them in your app! Your app should be working as shown in the figure below:



Section 3: Listening to Real-Time Events Using Live Query and Displaying on App

In this section, we monitor in real-time the “InputGPIO” class in the Parse Dashboard, and display the “content” of the objects for the user.

Start by defining a new EditText in the layout XML:

    android:maxLines ="2"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

In the scope of onCreate(), create a new EditText object and perform an initialization query (not live yet) immediately afterwards.

final EditText textInPin = (EditText) findViewById(R.id.status2Text);
textInPin.setText("Loading status of input pin...");

// Initial (non live) query to obtain last stored status of pin
ParseQuery<ParseObject> queryIn = ParseQuery.getQuery("InputGPIO");
queryIn.whereEqualTo("type", "interrupt");

queryIn.findInBackground(new FindCallback<ParseObject>() {
    public void done(List<ParseObject> objects, ParseException e) {
        if (e == null){
            textInPin.setText("Input is " + objects.get(0).getString("content"));
            textInPin.setText("Error: " + e.getMessage());

Note that the attributes of “InputGPIO” are content and type, the latter playing the role of destination on the “CommandGPIO” class.

At this point, your app should be looking like the figure shown below.


Now we will implement the Live Query. The tutorial referred to earlier is needed here.


Make sure you follow step 1 in our Live Query tutorial to select in which classes Live Query will be enabled and define a subdomain name. You may need to create the “InputGPIO” class (if it does not already exist) to enable the feature on it. Follow step 2 in the tutorial to set up the Live Query client on Android.

Remember to add the following imports:

import tgio.parselivequery.BaseQuery;
import tgio.parselivequery.LiveQueryClient;
import tgio.parselivequery.LiveQueryEvent;
import tgio.parselivequery.Subscription;
import tgio.parselivequery.interfaces.OnListener;

Add the following code to initialize LiveQuery and define its parameters.

// Initializing Live Query
LiveQueryClient.init("wss:YOUR_SUBDOMAIN_NAME.back4app.io", "YOUR_APP_ID", true );

// Defining attributes of LiveQuery
 Subscription subIn = new BaseQuery.Builder("InputGPIO")

When defining the subscription, we take only those elements whose type attribute is “interrupt” and retrieve the field content.

Now, add the following code to respond whenever an object defined by the subscription is created at Parse Server.

// Starting to listen to LiveQuery CREATE events, getting its content and writing
subIn.on(LiveQueryEvent.CREATE, new OnListener() {
    public void on(JSONObject object) {
        try {
            final String subInContent = (String) ((JSONObject) object.get("object")).get("content");
            runOnUiThread(new Runnable() {
                public void run() {
                   textInPin.setText("Input is " + subInContent);
                   Snackbar.make(findViewById(R.id.myCoordinatorLayout), "Input pin was changed to " + subInContent.toUpperCase(), Snackbar.LENGTH_LONG ).setAction("Action", null).show();
        } catch (JSONException e){

The content field of the object will be displayed in our new EditText element.

What we have done by this point is sufficient to display any input sent by the IoT device. However, to verify how the app is working, we will implement another kind of button, i.e., a Toggle Button that will create an “InputGPIO” class object and will save it on Parse Server.

Add the following code to the layout XML file:

    android:textOn = "input on"
    android:textOff = "input off"/>

Add the code mentioned below in the scope of onCreate() function, in MainActivity class.

// Toggle button is here just to emulate the objects the hardware would create
ToggleButton toggleTest = (ToggleButton) findViewById(R.id.toggleTest);
toggleTest.setOnClickListener( new OnClickListener(){
    public void onClick(final View view) {
        ParseObject command = new ParseObject("InputGPIO");
            gpioStatusTest = "on";
            gpioStatusTest = "off";

        command.put("content", "From Toggle: " + gpioStatusTest);
        command.saveInBackground(new SaveCallback(){
            public void done(ParseException e){
                Snackbar.make(view, "Changed input pin", Snackbar.LENGTH_LONG ).setAction("Action", null).show();

Also, declare the String in the MainActivity scope.

String gpioStatusTest = "off";

We are done with the app! At the end of this tutorial, your app should look quite similar to the figure shown below.


If you want to continue developing our IoT application, please read our IoT Series, a step-by-step guide, which teaches you the basics to set up a Raspberry Pi and specific applications, such as retrieving and saving objects from Parse Server using JavaScript.

Our codes are available in the following link:



Connecting Raspberry Pi to Parse Server

Setting Up Raspberry Pi


What tasks does the app do from the service side?

The tasks done by the Parse server side are the same which are done by Raspberry.  There are two major tasks,

-Writing of objects
-Performing of queries and live queries.

In which class we save our objects?

We save our objects in the class named as “CommandGPIO1”. These objects have further 3 attributes which are mentioned below.

– objectId
– createdAt

What are additional attributes CommandGPIO1 will have?

Our class “CommandGPIO1” will have two additional attributes. 


Content will have further two values which will be “on” and “off”. These values will be further sent to LED. For the destination attribute, all the objects will have string “command”. In this development given above we will define different strings for different LED’s.

IoT Series: Connecting Raspberry Pi to Parse Server with NodeJS


In our previous tutorial on IoT, we explained how to setup your Raspberry Pi and to write values to the GPIO pins. In this part, we will take a step towards a real IoT application, by opening a connection between Raspberry Pi and Parse Server and letting events on each side trigger actions on the other.

Here you will learn how to connect your Raspberry Pi to Parse Server using Back4App and to perform actions such as Queries, Live Queries and writing objects, and how the events on Parse Server may trigger real-world events!

We also provide our codes as a first step for you to develop your desired IoT Apps.


Of course, you need some electronic components. Three LEDs, three resistors (1k works fine), a breadboard and jumpers are sufficient.

You have to set up a Raspberry Pi environment. We strongly recommend you to follow our tutorial on Raspberry Pi, in the following link:


You must have a working app on Back4App. Follow Step 3 on the following tutorial if you still do not have.


You will also need to enable Live Query on your app. You may follow step 1 on the following tutorial if you have not enabled Live Query.


This code was designed to interact with the Android App described in this series of tutorials. However, you may choose to develop it independently and interact directly with Parse Dashboard to create/inspect objects.

Section 1: Responding to Real-Time events on Parse Server

We will use Live Query functionality, made easy in our Back4App dashboard, to listen to real-time events. The real-world response is an interaction with the pins on Raspberry using the onoff package. Make sure you have installed it using npm.

Import Gpio class to initialize each pin.

var Parse = require('parse/node');
var onoff = require('onoff');
var Gpio = onoff.Gpio;

var ledPower = new Gpio(4, 'out'), output1 = new Gpio(17, 'out');

ledPower is a LED that will always be on to indicate the application is running. output1 is the LED that will be turned on/off as a response to Live Query.

Please note our Raspberry Pi has the following the pin diagram, extracted from here.


There is a physical numbering corresponding to the numbers inside the circles and a GPIO specific numbering. For example, pin number 7 is GPIO4 and pin number 11 is GPIO17.

The integer argument on the constructor in the code above corresponds to the GPIO specific numbering! The second argument just sets it as an output pin. Please note that Raspberry Pi 2B outputs 3.3 V!

To turn on the power LED for the rest of the application, just add the following code.

   console.log('Application is ON');

We want the second LED to respond whenever a new object from “CommandGPIO1” class is created on Parse Server. It will turn on/off depending on its “content” attribute. Since we want it to respond in real-time, we will have to use LiveQuery.

Add the following code to start LiveQuery on NodeJS.

var LiveQueryClient = Parse.LiveQueryClient;
var client = new LiveQueryClient({
   applicationId: 'YOUR_APP_ID',
   serverURL: 'wss:YOUR_SUBDOMAIN_NAME.back4app.io/', // defined on LiveQuery section on Back4App dashboard
   javascriptKey: '',
   masterKey: ''
console.log("pre client.open");
console.log("post client.open");

The App ID can be found on “Core Settings” -> “Features” in your app dashboard. The serverURL is the same subdomain that you defined on LiveQuery in the app dashboard.

Now we have to define the query to be used with LiveQuery, and add the code to run when the event happens. Add the code below.

var query1 = new Parse.Query("CommandGPIO1");
var sub1 = client.subscribe(query1);
console.log("post sub1");
var count1 = 0;
sub1.on('create', (object) => {
   if(object.get("content") == 'off') count1 = 0;
   if(object.get("content") == 'on') count1 = 1;

   output1.write(count1, function(){
      console.log('Output 1 status changed to ' + count1);

Object query1 corresponds to a new query for objects from “CommandGPIO1” class. Make sure you allowed Live Query for this class on your app dashboard!

The following lines create the subscription and activate it for the creation of a new object of the corresponding class. The function called whenever this event happens sets the variable count1 as 0 or 1 for off or on contents, and it writes this logic voltage value to output1.

We are almost done with this part of the tutorial! Add the following code to turn off our application properly when the process is interrupted.

process.on('SIGINT', function (){
   console.log('Bye, bye! Turning off LEDs');

Section 2: Watching for Real-World Events and Acting on Parse Server


We will define a pin on Raspberry Pi as an input. When the voltage in the input becomes high or low, we will turn on/off a LED and write an object on Parse Server with content as “high” or “low”.

var input1 = new Gpio(21, 'in', 'rising'), output2 = new Gpio(23, 'out');

Note, for the input pin, we have to define a second argument to specify on which edge of the signal the pin will operate. 

Now we have to initialize Parse Server. Add the code below

Parse.serverURL = "https://parseapi.back4app.com";

We want to create “InputGPIO” class objects. The following code has a key role.

// Name of the class to be saved on Parse Server when event happens
var InputGPIO = Parse.Object.extend("InputGPIO");

// asynchronously reading from GPIO 21 (pin 40) on RPi 2B
// "value" can be either 0 (0 V) or 1 (3.3 V)

// Often multiple readings may come at once, even when the voltage on the pin is kept constant
// Therefore, the variable "valuePrev" is introduced to store the last voltage
// read from the pin and to trigger the desired actions only when it changes.
var valuePrev = -1;
input1.watch( function (err, value) {
      throw err;

   if(value != valuePrev){
      valuePrev = value;

     // Turning on/off a LED when another voltage is read in the input pin
     output2.write(value, function(){
        console.log('Output2 changed to: ' + value);

     // Creating new object
     var inputGPIO = new InputGPIO();

     if (value == 0){
        inputGPIO.set("content", "low");
        console.log("written low: " + value);
        inputGPIO.set("content", "high");
        console.log("written high: " + value);

     // Saving object to Parse Server
     inputGPIO.save().then( function(m){
     }).catch( function(err){

We start by extending Parse Object to the desired class, “InputGPIO”. Whenever a reading comes from the pin corresponding to input1, if it has a value different from the previous one:

  • This value is written to the pin corresponding to output2
  • An “inputGPIO” object with a proper content and type fields is created
  • The object is saved to Parse Server.

The logic involving value and valuePrev is useful because even when the voltage in the input pin is kept constant, multiple readings with the same state may continue to arrive.

We have almost finished! As in Section 1, we have to update the code to manage interruptions to the process.

process.on('SIGINT', function (){


To test this process, connect and later disconnect the pin on Raspberry that supplies 3.3 V to the pin defined as input.

To have a real IoT device, these node processes need to run automatically when the device boots. Please refer to the pm2 package, already mentioned in our Setting up Raspberry Pi tutorial.

We provide a working code for this tutorial. If you prefer, you may write separated codes for each task and run both simultaneously with pm2. Here is the link for our GitHub repository.


Our next tutorial will cover how to write an Android App that works with the code described here. The code is also available in the repository.


Setting up Raspberry Pi

Onoff library documentation on npm

Using onoff package


How will we respond to real time events on real time events on Parse server?

Live query functionality is being used. It is developed in the back4app dashboard and is easily accessible. The real world response is a sort of interaction between pins of Raspberry by using the “on” and “off” response. For doing this, you need to make sure that npm is installed already.

What are the Prerequisites required?

You need following things before starting.

-3 LEDs
-3 Resistors

These are some of the main things which are required before starting it out.

Where can you find an Apple ID and what is the server URL?

You need to go to your app dashboard and go to core settings> Features. The server URL is the sub domain you have defined on live query.

The code is provided above in the article which you need to add after defining the query to be used in Live Query.

Command Line Interface to Parse Server

Command Line Interface to Parse Server

The powerful Command Line Tool you’ve been using on Parse.com is now available at Back4App. You can continue to interact with your Parse Server using the Terminal. The Back4App CLI(command line interface) can be used to perform various actions on your Parse App like to create a new app, develop and deploy cloud code, manage app releases, set the SDK version, etc.

Parse.com vs Parse Server


Thanks to the forthcoming shutdown of the Parse server in January 2017 many developers wonder how they will keep their applications online from now on. This article focuses on the solution provided by Parse: the Parse-Server project. This is an open-source version of the Parse code, but with a few key differences.

To protect their data It’s extremely important for developers to migrate their apps to others solutions, such as Back4App .

Enrich Your Back4app User Experience


Parse Server technology continues to prove its value to app developers. It’s open-source cloud-based platform, support for local database development and testing, and its powerful backup and restore capabilities are just a few of the factors that underpin its rising popularity. The point has been reached where Parse Server now offers developers data storage possibilities, smooth integration with social media, and push notification capabilities far superior to those available on competing platforms.

Parse Server: a New Open Source Baas Framework


If you still haven’t settled on an alternative to Parse, the premier cross-platform BaaS that will be shutting down as of January 28, 2017, you’re not alone. Fortunately, Parse has open sourced the code as Parse Server and will let you create amazing mobile apps, expose REST APIs, and GraphQL APIs. Written in Node.js, Parse Server can serve the Parse API from any Node-enabled infrastructure.

Winning an APP Development Gold at Rio


The world’s athletes eagerly look forward to the opportunity to compete in the Rio Summer Olympics, but they are far from the only ones with high hopes of success in Brazil. The Olympics season also motivates mobile app developers to rush to bring out many new apps on Olympics-related themes. Developers have been submitting thousands of these new apps to the Google and Apple stores each day. The competition to create a winning mobile app is really just as tight as the rivalry on the athletics fields.

Cutting API Development Time by 80%


To better understand the growing appeal of third-party API provider offerings, we will take a closer look at an exciting new entrant to this vibrant market — the California-based www.back4app.com. They have just released a new back4app API Hub that allows developers to create easily, deploy, host and share APIs completely free of charge. The rapidly increasing pace of API development and the growing recognition of the commercial advantages of easy access to third-party API resources provide the hub’s raison d’être. The interest it has generated clearly testifies to the stress API developers now place on reducing development cycle time and its associated expenses.