2

I am new to mobile development and I'm stuck on this one.

Here are the requirements: Select a file from the device and upload it to some API. I tried the FilePicker Xamarin plugin from Studyxnet, but it throws an exception for the files selected from Google drive.

Then I tried to do it by myself. So, I need the file content (byte[]) and the filename. I could figure out the content by getting a stream from ContentResolver thanks to this post: Open a Google Drive File Content URI after using KitKat Storage Access Framework

Unfortunately, the part for getting the name doesn't work for me. The column indexes for both DISPLAY_NAME and SIZE are -1. The ICursor returned by ContentResolver.Query is Empty. It has 1 column, 1 row and on getString(0) it returns null.

I think it will be some permission thing, but can't get it to work. Here is my code:

var intent = new Intent();
intent.SetType("*/*");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(intent, "Select..."), 2);

OnActivityResult:

protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);

    var fileUri = data.Data;

    var bytes = await LoadAndConvertToByteArray(fileUri);

    var cursor = this.ContentResolver.Query(fileUri, null, null, null, null);

    var mimeType = this.ContentResolver.GetType(fileUri); // this works, I can get the mimeType
    int nameIndex = cursor.GetColumnIndex(OpenableColumns.DisplayName); // -1
    int sizeIndex = cursor.GetColumnIndex(OpenableColumns.Size); // -1

    cursor.MoveToFirst();

    var fileName = cursor.GetString(nameIndex); // exception
    var fileSize = cursor.GetString(sizeIndex); // exception

    //cursor.getString(0) returns null

    apiservice.UploadFile(fileName, bytes);
}
Community
  • 1
  • 1
  • 1
    `fileUri, null, null, null, null`. Think that you can specify on the place of the first null parameter a `projection` parameter indicating the fields you want to get returned by the cursor. – greenapps Feb 09 '17 at 16:11
  • `// exception`. You should not let it come to an exception. You can check for -1 your self and inform the user. – greenapps Feb 09 '17 at 16:12
  • http://stackoverflow.com/questions/20824762/android-how-to-use-getcontentresolver-query-for-multiple-columns – greenapps Feb 09 '17 at 16:16
  • `UploadFile(fileName, bytes);`. Confusing. Code has nothing to do with a file. I would call such a function UploadBytes(). – greenapps Feb 09 '17 at 16:19
  • Thank you @greenapps , your comments lead me to the solution. The projection parameter was blocking my results, because in original code I used projection on "_data". I double checked, in Xamarin.Android it throws an exception for `GetString(-1)` – Bicskei Tibor Feb 10 '17 at 12:13

0 Answers0