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

前端 未结 3 1659
有刺的猬
有刺的猬 2021-02-14 19:30

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

<
3条回答
  •  广开言路
    2021-02-14 19:51

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

提交回复
热议问题