Cloud Code for Android

In this tutorial, you create a Cloud Code Sample that sends a JSON Object to your Android App.

Step 1 – Create Cloud Code file

Create a new file and name it as ‘main.js’. Add the following code to the file:

Parse.Cloud.define("test", function(request, response) {
    var text = "hello world";
    var jsonObject = {
        "answer": text
    };
    response.success(jsonObject);
});

The first parameter of the Cloud Code is the function name. It is important to use the very same name you define inside the Cloud Code file into your Android App. You can also pass parameters to your function in your Android App. You can get these parameters by accessing them within the ‘request.params’ object.

Step 2 – Upload your code to Cloud Code

Go to your Dashboard, find the following option and click on Server:

Cloud Code

Next, click on “Choose file”, select the .js file, then click on “Save”:Cloud Code Upload

 

After that, your file will be uploaded. Then, it is necessary to add some code to your App.

Step 3 – Add Android Code:

To call the function, we have to create the parameters that will be passed to the function, pass in the name of the function, pass the parameters and then a function callback. The following code calls the function

// Use this map to send parameters to your Cloud Code function
// Just push the parameters you want into it
Map<String, String> parameters = new HashMap<String, String>();

// This calls the function in the Cloud Code
ParseCloud.callFunctionInBackground("test", parameters, new FunctionCallback<Map<String, Object>>() {

    @Override
    public void done(Map<String, Object> mapObject, ParseException e) {
         if (e == null) {
             // Everything went alright
         }
         else {
             // Something went wrong
         }
    }
});

The first parameter of ParseCloud.callFunctionInBackground is the function name on the Cloud Code and the second one is the HashMap that has every parameter that will be used by the function. The third argument is the callback that will be executed after the function has been called.

Finally, test it.

 

eITRDGR3qo