Over a million developers have joined DZone.

CloudBoost Android File Upload and Download

CloudBoost is a Database as a Service which provides an API that allows developers to store, query, search, and have real-time data on multiple clients. This is the first in a series of Android tutorials that I will be writing in order to share what I've accomplished with CloudBoost—in this tutorial, we are going to create a simple Android app for storing and fetching images.

· Cloud Zone

Download the Essential Cloud Buyer’s Guide to learn important factors to consider before selecting a provider as well as buying criteria to help you make the best decision for your infrastructure needs, brought to you in partnership with Internap.

What is CloudBoost?

CloudBoost is a Database as a Service. Its 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, Parse, will be closing business in early 2017. 

With all of these reasons, it's only wise for forward-looking developers to equip themselves with the CloudBoost ecosystem.

This is the first in a series of Android tutorials that I will be writing in order to share what I've accomplished with CloudBoost. If you have areas that you would like to see me cover in this series, don't hesitate to tell me in the comments. For further reference about CloudBoost, head over to the documentation page.

CloudBoost-ImageUpload-Android

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 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
  • socket.io client for java

All the jars listed above are available to you in the libs folder once 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 let's take a look at our main activity screen and understand the different views used.

Image title

  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 it's 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 the 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/her 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, setting it to area #2 which contains an ImageView.


activity_main.xml

Let's take a look at the layout XML that gives rise to this screen.

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Upload and download image" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/info"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="no image selected" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="fetchImage"
            android:text="pick image" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="uploadImage"
            android:text="Upload image" />
    </LinearLayout>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="downloadImage"
        android:text="Download from cloudboost" />



</LinearLayout>

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

MainActivity

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".

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              CloudApp.init("bengi123", "mLiJB380x9fhPRCjCGmGRg==");
              setContentView(R.layout.activity_main);
              info=(TextView) findViewById(R.id.info);
              image=(ImageView) findViewById(R.id.image);


       }

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

Fetching Image From Gallery

Image title

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.

Image title

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

        @Override
       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) {
                           info.setText(imageFile.getPath());
                     } else
                           Toast.makeText(this, "Failed to get image", Toast.LENGTH_SHORT)
                                         .show();
                     // imageView.setImageBitmap(bitmap);
              }
       }

Uploading Image to CloudBoost

Image title

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
               * */
              @Override
              protected void onPreExecute() {
                     super.onPreExecute();
                     UPLOAD = true;
                     DIALOG_MESSAGE = "uploading to CloudBoost";
                     showDialog(PROGRESS_BAR);
              }

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

                                  @Override
                                  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() {
                                                              info.setText(CLOUDBOOST_IMAGE_URL);
                                                       }
                                                });
                                         } 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
                     pDialog.setProgress(Integer.parseInt(progress[0]));
              }

              /**
               * After completing background task Dismiss the progress dialog
               * **/
              @Override
              protected void onPostExecute(String file_url) {
                     // dismiss the dialog after the file was downloaded
                     dismissDialog(PROGRESS_BAR);
              }

       }

Notice how we retrieve the saved image's URL and save it to a global variable with the following line CLOUDBOOST_IMAGE_URL=arg0.getFileUrl();

Image title

This URL will be used in the file download phase:

Image title

This stage is the easiest when it comes to the CloudBboost part of it. It's an everyday file download code, you just use CLOUDBOOST_IMAGE_URL.

Image title

You can download the complete source code and run here.

The Cloud Zone is brought to you in partnership with Internap. Read Bare-Metal Cloud 101 to learn about bare-metal cloud and how it has emerged as a way to complement virtualized services.

Topics:
mobile ,cloud ,dbaas ,android ,api

Published at DZone with permission of Bengi Egima, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}