Updated 21 December 2018
Here I am showing you how to get an image from your phone gallery. We use intents to open up the image gallery and get the image URI.
Add Permission in Android Manifest.
1 |
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
On click of the button, start startActivityForResult as follows:
1 2 3 4 |
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent, "Select Picture"),REQUEST_GET_SINGLE_FILE); |
Above code, the segment is used to choose an image from Gallery.
Once we will select an image, the method OnActivityResult()Â will be called. We need to handle the data in this method as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { if (resultCode == RESULT_OK) { if (requestCode == REQUEST_GET_SINGLE_FILE) { Uri selectedImageUri = data.getData(); // Get the path from the Uri final String path = getPathFromURI(selectedImageUri); if (path != null) { File f = new File(path); selectedImageUri = Uri.fromFile(f); } // Set the image in ImageView ImageView((ImageView) findViewById(R.id.imgView)).setImageURI(selectedImageUri); } } } catch (Exception e) { Log.e("FileSelectorActivity", "File select error", e); } } |
Get the real path from the URI
1 2 3 4 5 6 7 8 9 10 11 |
public String getPathFromURI(Uri contentUri) { String res = null; String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null); if (cursor.moveToFirst()) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); res = cursor.getString(column_index); } cursor.close(); return res; } |
Thanks for reading.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
7 comments
intent.addCategory(Intent.CATEGORY_OPENABLE);
It works even without this line.Could you tell what this line actually means?
And what should we actually specify as action?
Intent.ACTION_GET_CONTENT or Intent.ACTION_PICK or Intent.ACTION_OPEN_DOCUMENT?
Was Really much helpful to get the path…