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.