Downloading an Object Body

The following sample code shows how to download an object body with the transfer-at-once method.

  • // Instantiate the target KiiObject.
    Uri objUri = Uri.parse("Set the URI of an existing KiiObject here");
    KiiObject object = KiiObject.createByUri(objUri);
    
    // Specify the file destination.
    File localFile = new File(
            Environment.getExternalStorageDirectory(), "myImage.jpg");
    
    try {
      // Start downloading.
      object.downloadBody(localFile);
    } catch (IOException e) {
      // Handle the error.
    } catch (AppException e) {
      // Handle the error.
    }
  • // Instantiate the target KiiObject.
    Uri objUri = Uri.parse("Set the URI of an existing KiiObject here");
    KiiObject object = KiiObject.createByUri(objUri);
    
    // Specify the file destination.
    File localFile = new File(
            Environment.getExternalStorageDirectory(), "myImage.jpg");
    
    // Start downloading.
    object.downloadBody(localFile, new KiiObjectBodyCallback() {
      @Override
      public void onTransferStart(KiiObject kiiObject) {
      }
    
      @Override
      public void onTransferProgress(KiiObject object, long completedInBytes, long totalSizeinBytes) {
        float progress = (float) completedInBytes / (float) totalSizeinBytes * 100.0f;
      }
    
      @Override
      public void onTransferCompleted(KiiObject kiiObject, Exception exception) {
        if (exception != null) {
          // Handle the error.
          return;
        }
      }
    });

Here is what is happening in the sample code:

  • Create a KiiObject instance by calling the createByUri() method.
  • Create a reference to the target file (myImage.jpg).
  • Start downloading by calling the downloadBody() method.

The non-blocking onTransferProgress() method will be called as the download progresses. The method can reach 100% on the first call if the data size is small.

You might need to get rutime permissions for accessing an external storage during the object body downloading. See Getting runtime permissions for the implementation details.