Wednesday, 24 February 2016

CloudBoost Android File upload and download

NB: you can now read this post at my new site

What is CloudBoost

CloudBoost is a Database as a Service.  CloudBoost's primary service is a complete database which provides an API that allows developers to store, query, search, and have real-time data on multiple clients.
CloudBoost is increasingly becoming popular among developers; partly because of the inherent power that it avails to developers and partly because Facebook announced that its own mobile Backend as a Service in the name of Parse will be closing business in early 2017. 

With all this, its only wise for a forward looking developer to equip themselves with the CloudBoost ecosystem.
This is first in a series of Android tutorials I will be writing to share what I have done with cloudboost. If you have areas that you would like to see me cover in this series, don't hesitate to email me. For further reference about CloudBoost, headover to the documentation page.


In this tutorial, we are going to create a simple android app that does 5 things:

  1. Picks an image from the phone gallery
  2. Uploads this image to CloudBoost
  3. Downloads the image from the cloudboost
  4. saves the downloaded image to internal storage
  5. fetches the image from internal storage and shows it in an imageview

Tools used

  • eclipse indigo 3.7 with ADT 23.0.6
  • CloudBoost JavaSDK
  • okhttp-2.4.0
  • okhttp-ws-2.4.0
  • okio-1.4
  • client for java

All the jars listed above are available to you in the libs folder when you clone the JavaSDK. Please head over to github to do so.

create the app

Create a new android application in eclipse: File--new--android application project, call it CloudBoostImageApp.

We want a simple interface so that we focus on the core 5 items listed above, so lets take a look at our main activity screen and understand the different views used.

  1. This is just a TextView with static text declared in the activity_main.xml to act as the heading for our app.
  2. This is an empty ImageView area. When we pick our image from internal storage in item 5 of our specs, we shall set it to appear in this area.
  3. Another TextView, but this time its not static. We set text to it according to what stage we are at. At the beginning, it indicates "no image selected", when you have selected an image from gallery, its text changes to the URL of the selected file on the local file system. When you successfully upload the image to CloudBoost, its text changes to the URL of the image on cloudboost. We may also use it to show any error messages.
  4. Clicking this button calls the fetchImage() method which creates an intent to open the gallery so that the user can select an image of his choice, after selecting, we are brought back to this screen.
  5. Clicking this button uploads the image selected to cloudboost.
  6. Clicking this button downloads the uploaded image from cloudboost, and sets it to area #2 which contains an ImageView.


Lets take a look at the layout xml that gives rise to this screen.

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="Upload and download image" />

        android:layout_weight="1" />

        android:text="no image selected" />

        android:orientation="horizontal" >

            android:text="pick image" />

            android:text="Upload image" />

        android:text="Download from cloudboost" />


It's pretty self explanatory, so we shall look at the class.


In the onCreate method, we have to initialize our CloudApp with app_id and client_key, otherwise the SDk will tell use "app_id not found".

       protected void onCreate(Bundle savedInstanceState) {
              CloudApp.init("bengi123", "mLiJB380x9fhPRCjCGmGRg==");
              info=(TextView) findViewById(;
              image=(ImageView) findViewById(;


Please replace the app_id and client_key with your own from the dashboard.

Fetching Image from gallery

This stage needs 2 methods, namely:
       public void fetchImage(View view) {
              // Create intent to Open Image applications like Gallery, Google Photos
              Intent galleryIntent = new Intent(Intent.ACTION_PICK,                       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
              // Start the Intent
              startActivityForResult(galleryIntent, RESULT_LOAD_IMG);

This method creates an intent to select an image in the gallery and calls startActivityForResult.

When the selection is completed, onActivityResult is called, so you have to override it as well

       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              super.onActivityResult(requestCode, resultCode, data);
              if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                           && null != data) {
                     Bitmap bitmap = getImageFromPath(data.getData());
                     Log.d("ACTIVITRESULT", "bitmap:" + bitmap);

                     imageFile = bitmapToFile(bitmap, "cloudboostimage");
                     if (imageFile != null) {
                     } else
                           Toast.makeText(this, "Failed to get image", Toast.LENGTH_SHORT)
                     // imageView.setImageBitmap(bitmap);

uploading image to cloudboost

We create an async task to perform this operation in a background thread:
class uploadTask extends AsyncTask {

               * Before starting background thread Show Progress Bar Dialog
               * */
              protected void onPreExecute() {
                     UPLOAD = true;
                     DIALOG_MESSAGE = "uploading to CloudBoost";

               * uploading file in background thread
               * */
              protected String doInBackground(String... filename) {
                     if (imageFile == null) {
                           Toast.makeText(MainActivity.this, "No image file selected",
                           return null;
                     try {
                           CloudFile file = new CloudFile(imageFile);
                  CloudFileCallback() {

                                  public void done(CloudFile arg0, CloudException arg1)
                                                throws CloudException {
                                         if (arg0 != null) {
                                                Log.d("UPLOAD TASK", "file upload complete url="
                                                              + arg0.getFileUrl());
                                                CLOUDBOOST_IMAGE_URL = arg0.getFileUrl();
                                                runOnUiThread(new Runnable() {
                                                       public void run() {
                                         } else
                                                Log.d("UPLOAD TASK",
                                                              "File upload failed:" + arg1.getMessage());


                     } catch (Exception e) {
                           Log.e("Error: ", e.getMessage());

                     return null;

               * Updating progress bar
               * */
              protected void onProgressUpdate(String... progress) {
                     // setting progress percentage

               * After completing background task Dismiss the progress dialog
               * **/
              protected void onPostExecute(String file_url) {
                     // dismiss the dialog after the file was downloaded


Notice how we retrieve the saved image's URL and save it to a global variable with the following line


This URL will be used in the file download phase:

download file from cloudboost

This stage is the easiest when it comes to the cloudboost part of it. Its everyday file download code, you just use CLOUDBOOST_IMAGE_URL.
Downloaded and set to imageview

You can download complete source code and run.