Delphi + Android - Get the file path of image / video selected from media browser - Solved !!

Delphi + Android - Get the file path of image / video selected from media browser - Solved !!

Hi guys, after a full day of research (I know... I was slow!), I have find wrote the code that can open the media gallery and return the file path (along with all other information) of the media file selected. Hope this helps!



uses
...
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.Net,
Androidapi.Helpers,
FMX.Platform.Android,
FMX.Platform,
Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes,
....

//open the gallery
procedure TForm2.Button1Click(Sender: TObject);
var
Data : Jnet_Uri;
Intent : JIntent;
begin
FMessageSubscriptionID := TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification,
HandleActivityMessage);
Intent := TJIntent.Create;
Intent.setType(StringToJString('image/* video/*'));

Intent.setAction(TJIntent.JavaClass.ACTION_GET_CONTENT);
MainActivity.startActivityForResult(Intent, 0);
end;

// when message is received
procedure TForm2.HandleActivityMessage(const Sender: TObject;
const M: TMessage);
begin
if M is TMessageResultNotification then
HandleIntentAction(TMessageReceivedNotification(M).Value);
end;

// code to get the details of the file selected from gallery
function TForm2.HandleIntentAction(const Data: JIntent): Boolean;
var
P: TJavaObjectArray; // incase you want only specific fields... not used here. I have passed nil to get all the columns.
C: JCursor;
I: Integer;
begin
Memo1.Lines.Text := JStringToString(Data.getData.toString); // this returns the URI in string perfectly... so I know that I am getting the file path properly

// this is suppose to give the information back to C ( : JCursor)
C := MainActivity.getContentResolver.query(
Data.getData,
nil, // when projection is nil... it returns all columns. Ideally, you should only ask for the columns you need
StringToJString(''), // java accepts nuil... but you cannot give nil here, you need to give an empty JString
nil,
StringToJString('')); // java accepts nuil... but you cannot give nil here, you need to give an empty JString

C.moveToFirst;

Memo1.Lines.Add('Path:' + JStringToString(Data.getData.getPath));
Memo1.Lines.Add('No of columns returned:' + C.getColumnCount.ToString);

for I := 0 to C.getColumnCount - 1 do
begin
if JStringToString(C.getColumnName(I)) = '_data' then // '_data' column contains the path... you can use this to create the filestream to upload or do whatever....
Edit1.Text := JStringToString(C.getString(I));

// column name : column value formatted string
Memo1.Lines.Add(JStringToString(C.getColumnName(I)) +': ' + JStringToString(C.getString(I)));
end;
end;



Comments

Post a Comment