Saltar al contenido

¿Cómo mostrar la imagen en imageView seleccionada del almacenamiento interno?

Después de mucho luchar hemos dado con el resultado de esta duda que muchos lectores de este espacio han presentado. Si quieres compartir algún detalle no dejes de compartir tu información.

Solución:

Mira esto

     File imgFile = new  File("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
      if(imgFile.exists())

        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

        ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

        myImage.setImageBitmap(myBitmap);

      ;

E incluya este permiso en el archivo de manifiesto:




    ...
    
        ...
         
            ...
        
    
 

Para API 23+, debe solicitar los permisos de lectura/escritura incluso si ya están en su manifiesto.

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = 
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
;

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) 
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) 
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    

Y manejar la respuesta, algún ejemplo:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) 
    switch (requestCode) 
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: 
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) 

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

             else 

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            
            return;
        

        // other 'case' lines to check for other
        // permissions this app might request
    

Para obtener documentación oficial sobre la solicitud de permisos para API 23+, consulte https://developer.android.com/training/permissions/requesting.html

necesita agregar una verificación de permiso de tiempo de ejecución como esta:

    public  boolean isStoragePermissionGranted() 
    if (Build.VERSION.SDK_INT >= 23) 
        if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) 
            Log.v(TAG,"Permission is granted");
            return true;
         else 

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]Manifest.permission.READ_EXTERNAL_STORAGE, 1);
            return false;
        
    
    else  //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    

úsalo como:

if(isStoragePermissionGranted())
 Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
 image.setImageBitmap(bm);

 

Captura el resultado en

    @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED)
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
        Bitmap bm = BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");
       image.setImageBitmap(bm);
    

Comentarios y calificaciones del tutorial

Tienes la opción de sostener nuestro ensayo fijando un comentario y dejando una puntuación te damos las gracias.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *