How to use Parse Backend in Android App

I have built mobile apps that have used external database like MYSQL to store the app’s data. I used Php with sql query to query the database then the output is converted to JSON which is use by the android apps to display the data on the apps.

I realized it needs much work and the connection is very slow sometimes. I decided to give an android backend cloud storage system a try. After much search and research I settled for Parse. If you have not heard of Parse before you can move over to their website and read more about Parse here.

In this tutorial, I will demonstrate how we can use a Parse backend to create a game or app score feature. Imagine we have a quiz application and we wanted a situation where by our app users can decide to store the result they obtained after taking a quiz. In return, your app users will see the top five highest scorers in the quiz.

Basically, after taking the quiz the user will click a button to send the quiz result to Parse cloud storage and the user can check if his or her score is among the top five scores.

If you are new to android, I will suggest you first read our beginner’s android tutorials to get familiar with android mobile application development 

The first thing we will start with is to create a new android project. I am using Eclipse IDE for my android development. You are free to use whatever IDE you are familiar with.

After you have created your project, we will head over to Parse website to create an account and download Parse SDK for android. If you have done this before you can ignore this section and move over to the next task.

I have included the content of the Parse SDK for android and you can also download it through the link provided. Please note that we are making use of Parse free service.

Setting up Parse Android SDK in your android Application

  • The Parse android SDK we are using for this tutorial is version 1.7
  • Add the Parse android SDK in your application lib folder
  • In Eclipse IDE, right click your application folder
  • In the pop-up menu that appears, click on properties
  • Then click on Java Build Path
  • Choose libraries tab and click on add jars button
  • Navigate through your folder to your application lib folder and select the Parse android SDK
  • Click on order and export tab
  • And finally click the Ok button.

Now you have successfully added the Parse android SDK in your application.

To test if it is working i.e. if your application can communicate with your Parse backend, we will carry out this simple task.

Copy and paste this code in your MainActivity onCreate callback method. Please note that you will replace the parameters with your correct Parse keys.

public class MainActivity extends Activity {

    @Override

    public void onCreate() {

        super.onCreate();

            Parse.initialize(this, "7zBztvyG4hYQ9XzRrroro3SMBYWAj0GUL", "iZWhgJRu6yKakas7m3NCV3qedijWL");

    }                  

}

Since the communication between your app and Parse backend requires internet connection, remember to add these permissions in your application Manifest file.

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Now we will do the final testing with this code snippet below

public class MainActivity extends Activity {

        @Override

    public void onCreate() {

        super.onCreate();

            // Add your initialization code here

            Parse.initialize(this, "7zBztvyG4hXghgfqYxfSMBYWAj0GUL", "iZWhgJRu6yK67muLcNCV3qedijWL");
 

        // Test creation of object

            ParseObject testObject = new ParseObject("TestObject");

            testObject.put("foo", "bar");

            testObject.saveInBackground();
    }                  
}

What we want to achieve with this code is to create a textObject which is an instance of a ParseObject with a property called foo. bar is assigned as the value of the foo property. The saveInBackground() method will save the piece of information in our Parse backend.

If you have succeed in doing it then you will see this information display when you click the test button.

parse

Now that everything is working out for us we will go ahead and create our score class in our Parse Dashboard.

Create a class and name it Score

Add a column to the class called name which is a String type

Add another column to the class called score which is a number type

Now let’s head back to our android application.

public class MainActivity extends Activity {

            private EditText urUsername;

            private String enteredName;

             @Override

            protected void onCreate(Bundle savedInstanceState) {

                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.activity_submit_result_online);

                 Parse.initialize(this, "7zBztvyG4hXghgfqYxfSMBYWAj0GUL", "iZWhgJRu6yK67muLcNCV3qedijWL");

                urUsername = (EditText)findViewById(R.id.enter_your_username);

                Button submitResultOnline = (Button)findViewById(R.id.submit_quiz_result);

                        submitResultOnline.setOnClickListener(new OnClickListener(){

                                    @Override

                                    public void onClick(View view) {

                                                enteredName = urUsername.getText().toString();

                                                if(enteredName.equals("")){

                                      Toast.makeText(getApplicationContext(), "Username Field must be filled", Toast.LENGTH_LONG).show();

                                                      return;

                                                }

                                                if(enteredName.length() < 4 || enteredName.length() > 6){           

                                                      Toast.makeText(getApplicationContext(), "Username must contain between 4 - 6 characters", Toast.LENGTH_LONG).show();

                                                      return;

                                                }                                              

                                    // check if there is avaliability of internet network

                                if(Ultility.isNetworkAvailable(getApplicationContext())){

                                                int mScore = getScore();

                                                ParseObject score = new ParseObject("Score");

                                                score.put("name", enteredName);

                                                score.put("score", mScore);

                                                score.saveInBackground();

                                     }else{

                                    Toast.makeText(getApplicationContext(), "No available internet connection.", Toast.LENGTH_LONG).show();

                                                return;

                                    }                                              

                             }

                        });

            }

To display the list of five highest scores in the quiz, We will use a similar code. You can read Parse’s user manual to see amazing services they offer.

@Override

            protected void onCreate(Bundle savedInstanceState) {                    

                super.onCreate(savedInstanceState);

                        setContentView(R.layout.activity_quiz_top_scorers);                       

                        topScorers = (ListView)findViewById(R.id.top_scorers);                   

                        Parse.initialize(this, "7zBztvyG4hXghgfqYxfSMBYWAj0GUL", "iZWhgJRu6yK67muLcNCV3qedijWL"););

                        ParseQuery<Score> query = ParseQuery.getQuery(Score.class);

                        query.orderByDescending("score");

                        query.setLimit(5);

                        query.findInBackground(new FindCallback<Score>(){

                                    @Override

                                    public void done(List<Score> topScores, ParseException e) {

                                                // TODO Auto-generated method stub

                                                if(null == e){

                                                            Log.d("score", "" + topScores.size());

                                                            topScorers.setAdapter(new TopScoersAdapter(getApplicationContext(), R.layout.top_scorers_list, topScores));

                                                }

                                                else{

                                                            Log.d("Seminar Object ", "Error: " + e.getMessage());

                                                }

                                    }

                        });

That is the end. But there is so much you can use Parse for. If you have questions or any suggestion, please kindly use the comment box below.

Add a Comment