skip to Main Content

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);

Database

2

Answers


  1. Chosen as BEST ANSWER

    Here how I solved the problem, -I thing fileUri.getLastPathSegment() it's returning the content of the file. Get File Name method :

    1. I defined Cursor:

          Cursor cursor = getContentResolver().query(fileUri,null, null, null, null);
      
    2. nameIndex:

       int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
       cursor.moveToFirst();
       String filename =  cursor.getString(nameIndex);
      

  2. ACTION_GET_CONTENT is documented to give you a Uri with a content scheme. Your code assumes that the Uri has a file 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 the Uri to DocumentFile.fromSingleUri(), then calling getName() on that DocumentFile, 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 the DocumentFile, then use MimeTypeMap to try to get a file extension commonly associated with the MIME type of the content.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search