Updated 27 July 2021
In this tutorial we will discuss How File Chooser works in Android Studio . File Chooser allow users to select a file which is in phone memory.
Layout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <androidx.appcompat.widget.AppCompatImageView android:layout_width="wrap_content" android:id="@+id/upload_attachment" android:src="@drawable/upload_pic" android:layout_height="wrap_content"/> <androidx.appcompat.widget.AppCompatTextView android:layout_width="match_parent" android:id="@+id/upload_attachment_tv" android:layout_height="wrap_content"/> </androidx.appcompat.widget.LinearLayoutCompat> |
In activity_main layout we take an ImageView and a textview. When we upload image then in textview we show file name and file path.
AndroidManifest
1 2 |
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> |
we need to provide permission for read external storage so we added permission.
MainActivity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
class MainActivity : AppCompatActivity() { private val MY_REQUEST_CODE_PERMISSION = 1000; private val MY_RESULT_CODE_FILECHOOSER = 2000; private lateinit var mButton: Button; private lateinit var uploadAttachmentTv:TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mButton = findViewById(R.id.upload_button) uploadAttachmentTv=findViewById(R.id.upload_attachement_tv) mButton.setOnClickListener(View.OnClickListener { askPermissionAndBrowseFile() }) } fun askPermissionAndBrowseFile() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val permisson: Int = ActivityCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) if (permisson != PackageManager.PERMISSION_GRANTED) { requestPermissions( arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), MY_REQUEST_CODE_PERMISSION ) return } } showFileChooser() } private fun showFileChooser() { val mimeTypes = arrayOf("image/jpeg", "image/png", "image/gif", "application/pdf") val intent = Intent(Intent.ACTION_GET_CONTENT) intent.addCategory(Intent.CATEGORY_OPENABLE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent.type = if (mimeTypes.size == 1) mimeTypes[0] else "*/*" if (mimeTypes.isNotEmpty()) { intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) } } else { var mimeTypesStr = "" for (mimeType in mimeTypes) { mimeTypesStr += "$mimeType|" } intent.type = mimeTypesStr.substring(0, mimeTypesStr.length - 1) } startActivityForResult( Intent.createChooser(intent, "choose file"), MY_RESULT_CODE_FILECHOOSER ) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == AppCompatActivity.RESULT_OK) { if (requestCode == MY_RESULT_CODE_FILECHOOSER) { val fileName = FileUtils.getFileName(data?.data!!) val filepath=FileUtils.getPath(this,data.data!!) uploadAttachmentTv.setText("fileName="+fileName+"\nfilePath="+filepath); } } } } |
In MainActivity we ask for permission and if there is already permission we can pick file. We are creeating new Intent ACTION_GET_CONTENT. we also added CATEGORY_OPENABLE for open category and then call startActivityForResult.
Here we will get data in onActivityResult function and here we check if request code is equals to MY_RESULT_CODE_FILECHOOSER then we will get file data. We can fetch data from FileUtils class.If we need file name and file path then we will call FileUtils function getFilleName and getPath().
FileUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
public class FileUtils { public static String getPath(Context ctx, Uri uri) { String ret; try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { ret = getUriRealPathAboveKitkat(ctx, uri); } else { ret = getRealPath(ctx.getContentResolver(), uri, null); } } catch (Exception e) { e.printStackTrace(); Log.d("DREG", "FilePath Catch: " + e); ret = getFilePathFromURI(ctx, uri); } return ret; } private static String getFilePathFromURI(Context context, Uri contentUri) { String fileName = getFileName(contentUri); if (!TextUtils.isEmpty(fileName)) { String TEMP_DIR_PATH = Environment.getExternalStorageDirectory().getPath(); File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName); Log.d("DREG", "FilePath copyFile: " + copyFile); copy(context, contentUri, copyFile); return copyFile.getAbsolutePath(); } return null; } public static String getFileName(Uri uri) { if (uri == null) return null; String fileName = null; String path = uri.getPath(); int cut = path.lastIndexOf('/'); if (cut != -1) { fileName = path.substring(cut + 1); } return fileName; } public static void copy(Context context, Uri srcUri, File dstFile) { try { InputStream inputStream = context.getContentResolver().openInputStream(srcUri); if (inputStream == null) return; OutputStream outputStream = new FileOutputStream(dstFile); IOUtils.copyStream(inputStream, outputStream); // org.apache.commons.io inputStream.close(); outputStream.close(); } catch (Exception e) { // IOException e.printStackTrace(); } } @RequiresApi(api = Build.VERSION_CODES.KITKAT) private static String getUriRealPathAboveKitkat(Context ctx, Uri uri) { String ret = ""; if (ctx != null && uri != null) { if (isContentUri(uri)) { if (isGooglePhotoDoc(uri.getAuthority())) { ret = uri.getLastPathSegment(); } else { ret = getRealPath(ctx.getContentResolver(), uri, null); } } else if (isFileUri(uri)) { ret = uri.getPath(); } else if (isDocumentUri(ctx, uri)) { String documentId = DocumentsContract.getDocumentId(uri); String uriAuthority = uri.getAuthority(); if (isMediaDoc(uriAuthority)) { String idArr[] = documentId.split(":"); if (idArr.length == 2) { String docType = idArr[0]; String realDocId = idArr[1]; Uri mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; if ("image".equals(docType)) { mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(docType)) { mediaContentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(docType)) { mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } String whereClause = MediaStore.Images.Media._ID + " = " + realDocId; ret = getRealPath(ctx.getContentResolver(), mediaContentUri, whereClause); } } else if (isDownloadDoc(uriAuthority)) { Uri downloadUri = Uri.parse("content://downloads/public_downloads"); Uri downloadUriAppendId = ContentUris.withAppendedId(downloadUri, Long.valueOf(documentId)); ret = getRealPath(ctx.getContentResolver(), downloadUriAppendId, null); } else if (isExternalStoreDoc(uriAuthority)) { String idArr[] = documentId.split(":"); if (idArr.length == 2) { String type = idArr[0]; String realDocId = idArr[1]; if ("primary".equalsIgnoreCase(type)) { ret = Environment.getExternalStorageDirectory() + "/" + realDocId; } } } } } return ret; } @RequiresApi(api = Build.VERSION_CODES.KITKAT) private static boolean isDocumentUri(Context ctx, Uri uri) { boolean ret = false; if (ctx != null && uri != null) { ret = DocumentsContract.isDocumentUri(ctx, uri); } return ret; } private static boolean isContentUri(Uri uri) { boolean ret = false; if (uri != null) { String uriSchema = uri.getScheme(); if ("content".equalsIgnoreCase(uriSchema)) { ret = true; } } return ret; } private static boolean isFileUri(Uri uri) { boolean ret = false; if (uri != null) { String uriSchema = uri.getScheme(); if ("file".equalsIgnoreCase(uriSchema)) { ret = true; } } return ret; } private static boolean isExternalStoreDoc(String uriAuthority) { boolean ret = false; if ("com.android.externalstorage.documents".equals(uriAuthority)) { ret = true; } return ret; } private static boolean isDownloadDoc(String uriAuthority) { boolean ret = false; if ("com.android.providers.downloads.documents".equals(uriAuthority)) { ret = true; } return ret; } private static boolean isMediaDoc(String uriAuthority) { boolean ret = false; if ("com.android.providers.media.documents".equals(uriAuthority)) { ret = true; } return ret; } private static boolean isGooglePhotoDoc(String uriAuthority) { boolean ret = false; if ("com.google.android.apps.photos.content".equals(uriAuthority)) { ret = true; } return ret; } @SuppressLint("Recycle") private static String getRealPath(ContentResolver contentResolver, Uri uri, String whereClause) { String ret = ""; Cursor cursor = contentResolver.query(uri, null, whereClause, null, null); if (cursor != null) { boolean moveToFirst = cursor.moveToFirst(); if (moveToFirst) { String columnName = MediaStore.Images.Media.DATA; if (uri == MediaStore.Images.Media.EXTERNAL_CONTENT_URI) { columnName = MediaStore.Images.Media.DATA; } else if (uri == MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) { columnName = MediaStore.Audio.Media.DATA; } else if (uri == MediaStore.Video.Media.EXTERNAL_CONTENT_URI) { columnName = MediaStore.Video.Media.DATA; } int columnIndex = cursor.getColumnIndex(columnName); ret = cursor.getString(columnIndex); } } return ret; } } |
We can get FileName and FilePath from this class.We are using IOUtils so we need to add dependency for this.
dependency for IOUtils
1 2 |
api 'com.google.android.gms:play-services-mlkit-text-recognition:16.2.0' |
Please check attached image here we pick a file and you can see we are showing file name and file path in textview.
So Here we discussed How File Chooser works in Android Studio. Thanks for reading this blog and You can get other blogs from here
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.