Activity Forums Salesforce® Discussions How to upload file using Salesforce Mobile SDK for Android? Reply To: How to upload file using Salesforce Mobile SDK for Android?

  • Parul

    September 20, 2018 at 1:23 am


    Ok. I figured this out. First, create the parent object (the main form data) using the following.

    request = RestRequest.getRequestForCreate(apiVersion, objectType, fields);
    client.sendAsync(restRequest, new RestClient.AsyncRequestCallback() {...

    In the onSuccess method you will get the id of the new object from the response. There are plenty of examples that show how to get the JSON object and the id. Armed with this parentId we can now create the attachment. The code looks something like this.

    private void postImageAsAttachment(String parentId, String title) {
    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put("Name", title);
    fields.put("ParentId", parentId);
    fields.put("Body", ImageHelper.getBase64FromImage(mCurrentPhotoPath));

    RestRequest request = null;
    try {
    request = RestRequest.getRequestForCreate(apiVersion, "Attachment", fields);
    } catch (Exception ex) {
    Log.d(TAG, "sendRequest: ", ex);
    Toast.makeText(MainActivity.this, "The file upload failed: " + ex.toString(), Toast.LENGTH_LONG).show();
    client.sendAsync(request, new RestClient.AsyncRequestCallback() {...

    I'm using a simple class called ImageHelper that simply loads the image file, performs image compression (if necessary), and base64 encodes the image data. The result is that an "Attachment" object is created as a child of the parent object.