Abhilash Harsole
Abhilash Harsole

Reputation: 254

Select pdf file from phone on button click and display its file name on textview

I want to select pdf file from phone on button click and display its file name on a text view. till now I have done opening file manager for selecting pdf on button click

btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("application/pdf");
            startActivity(intent);
        }
    });

how do I get the selected file name on textview??

Upvotes: 13

Views: 31786

Answers (5)

kgandroid
kgandroid

Reputation: 5595

startActivityForResult(intent, CODE) is deprecated.

The newer solution:

private fun pickFileFromGallery() {
        val intent = Intent()
        intent.action = Intent.ACTION_GET_CONTENT
        intent.type = "application/pdf"
        galleryResult.launch(intent)
    }

And then write the galleryResult just below the class:

private val galleryResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                result: ActivityResult ->
            if (result.resultCode == Activity.RESULT_OK) {
                Log.d("Result",result.data?.data.toString())
            }
        }

Upvotes: 2

Kuldeep Rathod
Kuldeep Rathod

Reputation: 31

click Hand

val intentPDF = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                type = "application/pdf"
                addCategory(Intent.CATEGORY_OPENABLE)
                putExtra(DocumentsContract.EXTRA_INITIAL_URI, true)
            }
            startActivityForResult(
                Intent.createChooser(intentPDF, "Open with"),
                1001
            )

In onActivityResult

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        when (requestCode) {
          
            1001-> {
                data?.let {
                    it.data?.also{uri ->
                        val intent = Intent(Intent.ACTION_VIEW,uri)
                        intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                        if (intent.resolveActivity(getPackageManager()) == null) {
                            Toast.makeText(this,"No app found to open Document!", Toast.LENGTH_SHORT).show()
                        } else {
                            startActivity(intent)
                        }`

                    }
                }

Upvotes: 2

Sibaditya Maiti
Sibaditya Maiti

Reputation: 121

You can do the following:

@Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    String fileName = getFileName(this, data.getData());

    yourTextView.setText(fileName);
}



public String getFileName(Context context, Uri uri) {
    if (uri != null && context != null) {
      Cursor returnCursor =
          context.getContentResolver().query(uri, null, null, null, null);
      if(returnCursor != null) {
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        if(nameIndex >= 0 && sizeIndex >= 0){
          Log.d("File Name : " + returnCursor.getString(nameIndex));
          Log.d("File Size : " + Long.toString(returnCursor.getLong(sizeIndex)));
          Boolean isValidFile = checkFormat(returnCursor.getString(nameIndex));

          if(!isValidFile){
            return returnCursor.getString(nameIndex);
          }
  }

private Boolean checkOtherFileType(String filePath){
    if(!Utility.isNullOrEmpty(filePath)) {
      String filePathInLowerCase = filePath.toLowerCase();
      if(filePathInLowerCase.endsWith(".pdf")) {
        return true;
      }
    }
    return false;
  }

Hope this will help you out

Upvotes: 3

Nikhil
Nikhil

Reputation: 3711

use startActivityForResult(intent, 1212) at the place of startActivity(intent); and do the foll0wing in onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case 1212:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            String path = myFile.getAbsolutePath();
            String displayName = null;

            if (uriString.startsWith("content://")) {                   
                Cursor cursor = null;
                try {                           
                    cursor = getActivity().getContentResolver().query(uri, null, null, null, null);                         
                    if (cursor != null && cursor.moveToFirst()) {                               
                        displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    }
                } finally {
                    cursor.close();
                }
            } else if (uriString.startsWith("file://")) {           
                displayName = myFile.getName();
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

Upvotes: 28

Preetika Kaur
Preetika Kaur

Reputation: 2031

Add in your getPDFPath method:

public String getPDFPath(Uri uri){

     final String id = DocumentsContract.getDocumentId(uri);
     final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

     String[] projection = { MediaStore.Images.Media.DATA };
     Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     cursor.moveToFirst();
     return cursor.getString(column_index);
}

In your case, this code is specifically for documents from DonwloadProvider, for further implementation check Paul Burke answer. I personally use his aFileChooser library to avoid this kind of problems.

Hope this helps!

Upvotes: 2

Related Questions