I have an app connected to firebase realtime database. When I am trying to get file path and extension by the following methods, it shows the different name and also show same thing for extension.
Method used to get filename and path:
fileUri = data.getData();
String path = fileUri.getLastPathSegment();
String filename = path.substring(path.lastIndexOf("/")+1);
String extension = path.substring(path.lastIndexOf(".")+1);
StorageReference filepath = storageReference.child(messagePushID + "." + extension);
filepath.putFile(fileUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
{
if (task.isSuccessful())
{
Map messageDocBody = new HashMap();
messageDocBody.put("message", task.getResult().toString());
messageDocBody.put("name",path);
messageDocBody.put("type",checker);
messageDocBody.put("extension",extension);
messageDocBody.put("to",messageReceiverID);
messageDocBody.put("from",messageSenderID);
messageDocBody.put("time",time);
messageDocBody.put("date",date);
messageDocBody.put("messageID",messagePushID);
2
Answers
Here how I solved the problem, -I thing
fileUri.getLastPathSegment()
it's returning the content of the file. Get File Name method :I defined Cursor:
nameIndex:
ACTION_GET_CONTENT
is documented to give you aUri
with acontent
scheme. Your code assumes that theUri
has afile
scheme and represents a filesystem path.There is no guaranteed way to get a display name for such a
Uri
, and there is no requirement that the display name be a filename with a file extension. The content that the user chooses might never have been a file in the first place. You are welcome to try passing theUri
toDocumentFile.fromSingleUri
(), then callinggetName()
on thatDocumentFile
, to get a display name.In terms of file extensions, in addition to trying to parse one out of the display name, you could call
getType()
on theDocumentFile
, then useMimeTypeMap
to try to get a file extension commonly associated with the MIME type of the content.