Error saving the path of the new .png created in Sqlite

2

I create a new .png of the image that I select from the Gallery and try to save the path in my Sqlite but I close the application once selected the image of the Gallery.

EditarPersonaActivity

    public class EditarPersonaActivity extends Activity {

        private Button butonGuardar;
        private DatabaseHandler baseDatos;
        private Bundle extras;
        private ImageView imagenPersona;
        private String ruta_imagen; // La ruta de la imagen que el usuario eligio
        private int SELECCIONAR_IMAGEN = 244;
        private int PICK_IMAGE_REQUEST = 1;
        private static final String TAG = "EditarPersonaActivity";
        private int id_imagen;


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.editar_persona);

            butonGuardar = (Button) findViewById(R.id.botonGuardar);
            imagenPersona = (ImageView) findViewById(R.id.imagenPersona);

            // imagen onclick para abrir la galería y donde se muestra la imagen seleccionada

            imagenPersona.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    ventanaImagen();
                }
            });

            // Recupera en un Objeto Bundle si tiene valores que fueron pasados como
            // parametro de una actividad.
            extras = getIntent().getExtras();

    // comprueba los datos al editar la persona

            if (estadoEditarPersona()) {
                ruta_imagen = extras.getString("ruta_imagen");
                imagenPersona.setImageBitmap(crearThumb());
            }

            // Agrega nuevo registro de una persona.
            butonGuardar.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    /// comprueba el estado para editar la persona
                            if (estadoEditarPersona()) {

                    /// edita la persona
                        editarPersona();
                    } else {
                        // añade la persona

                        insertarNuevoPersona();
                    }
                    // finaliza la actividad
                    finish();
                }


            });
        }

        /// metodo para crear la persona

        private void insertarNuevoPersona() {
            baseDatos = new DatabaseHandler(EditarPersonaActivity.this);

            try {
                // Crear objeto Persona.
                Persona persona = new Persona(ruta_imagen);

                // Se inserta una nueva persona.
                baseDatos.insertarPersona(persona);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // Se cierra la base de datos.
                baseDatos.cerrar();
            }
        }

    // metodo para editar la persona

        private void editarPersona() {
            baseDatos = new DatabaseHandler(EditarPersonaActivity.this);
            try {
                // Crear objeto persona.
                int id = extras.getInt("id");
                Persona persona = new Persona(id, ruta_imagen);
                baseDatos.actualizarRegistros(id, persona.getRutaImagen());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                baseDatos.cerrar();
            }
        }


        /// estado al editar la persona

        public boolean estadoEditarPersona() {
            // Si extras es diferente a null es porque tiene valores. En este caso
            // es porque se quiere editar una persona.
            if (extras != null) {
                return true;
            } else {
                return false;
            }
        }


         // Metodo que abre la galeria

        private void ventanaImagen() {
            try {
                final CharSequence[] items = { "Seleccionar de la galería" };

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Seleccionar una foto");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        switch (item) {
                            case 0:
                                Intent intent = new Intent();
                                // Show only images, no videos or anything else
                                intent.setType("image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                // Always show the chooser (if there are multiple options available)
                                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
                                break;
                        }
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } catch (Exception e) {
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);


            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

                Uri selectedImage = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                    ///Muestra imagen seleccionada de galería en ImageView.


                    //Define path donde sera guardada una nueva imagen con medidas 150x150px
                    File dir = Environment.getExternalStoragePublicDirectory("/Download");
                    File file = new File(dir, (id_imagen++) + ".png");

                    if (!file.exists()) { //Si archivo no existe.
                        try {
                            file.createNewFile(); //Procede a crearlo.
                        } catch (IOException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    }

                    if (bitmap != null) {

                        //Redimensiona imagen.
                        Bitmap bitmapout = Bitmap.createScaledBitmap(bitmap, 150, 150, false);
                        FileOutputStream fOut = null;
                        try {
                            fOut = new FileOutputStream(file);
                            bitmapout.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                            fOut.flush();
                            fOut.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            Log.e(TAG, e.getMessage());
                        }

                        //Muestra imagen con nuevas medidas en ImageView.

                        ImageView imageView = (ImageView) findViewById(R.id.imagenPersona);
                        imageView.setImageBitmap(bitmapout);

 // intento guardar la ruta del .png creado en la DB
                    ruta_imagen = obtieneRuta(selectedImage);
                    imageView.setImageBitmap(crearThumb());


                    } else {
                        Toast.makeText(this, "Error obteniendo imagen", Toast.LENGTH_LONG).show();
                    }


                } catch (IOException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        }

        private Bitmap getBitmap(String ruta_imagen) {
            // Objetos.
            File imagenArchivo = new File(ruta_imagen);
            Bitmap bitmap = null;

            if (imagenArchivo.exists()) {
                bitmap = BitmapFactory.decodeFile(imagenArchivo.getAbsolutePath());
            }
            return bitmap;
        }


        private String obtieneRuta(Uri uri) {
            String[] projection = { android.provider.MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor
                    .getColumnIndexOrThrow(android.provider.MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }

        private Bitmap crearThumb(){
            Bitmap bitmap = getBitmap(ruta_imagen);
            BitmapFactory.Options opciones = new BitmapFactory.Options();
            opciones.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(ruta_imagen, opciones);

            int scaleW = opciones.outWidth / 854 + 1;
            int scaleH = opciones.outHeight / 480 + 1;
            int scale = Math.max(scaleW, scaleH);

            opciones.inJustDecodeBounds = false;
            opciones.inSampleSize = scale;
            opciones.inSampleSize = scale;
            bitmap = BitmapFactory.decodeFile(ruta_imagen, opciones);
            return bitmap;
        }
    }

Logcat

 java.lang.RuntimeException: Failure delivering result ResultInfo {
  who = null, request = 1, result = -1, data = Intent {
    dat = content: //com.android.providers.media.documents/document/image:12016 flg=0x1 }} to activity {prueba.laboratorioimagen/prueba.laboratorioimagen.EditarPersonaActivity}: java.lang.NullPointerException
     at android.app.ActivityThread.deliverResults(ActivityThread.java: 4104)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java: 4147)
    at android.app.ActivityThread. - wrap20(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1544)
    at android.os.Handler.dispatchMessage(Handler.java: 102)
    at android.os.Looper.loop(Looper.java: 154)
    at android.app.ActivityThread.main(ActivityThread.java: 6176)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 888)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 778)
    Caused by: java.lang.NullPointerException
    at java.io.File. < init > (File.java: 262)
    at prueba.laboratorioimagen.EditarPersonaActivity.getBitmap(EditarPersonaActivity.java: 230)
    at prueba.laboratorioimagen.EditarPersonaActivity.crearThumb(EditarPersonaActivity.java: 250)
    at prueba.laboratorioimagen.EditarPersonaActivity.onActivityResult(EditarPersonaActivity.java: 215)
    at android.app.Activity.dispatchActivityResult(Activity.java: 6932)
    at android.app.ActivityThread.deliverResults(ActivityThread.java: 4100)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java: 4147) 
    at android.app.ActivityThread. - wrap20(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java: 1544) 
    at android.os.Handler.dispatchMessage(Handler.java: 102) 
    at android.os.Looper.loop(Looper.java: 154) 
    at android.app.ActivityThread.main(ActivityThread.java: 6176) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 888) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 778) 
    
asked by UserNameYo 25.02.2017 в 14:32
source

1 answer

1

There are two details, the first is that from OS 6.0 you must manually require write permissions, not only define them in the AndroidManifest.xml.

private int CODIGO_RESULT_EDITAR_PERSONA = 0;
private void checkWritePermission(){
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        // No action!.
    }else{
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS);
        return;
    }
}


public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case REQUEST_CODE_ASK_PERMISSIONS:
            if(grantResults[0] != PackageManager.PERMISSION_GRANTED){
                // Permiso negado.
            }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

You call the checkWritePermission(); method when you start your application ( onCreate() ) or before performing read and write operations.

The second problem is that the path of the image (created file) is obtained simply by means of getAbsolutePath () :

//ruta_imagen = obtieneRuta(selectedImage);
ruta_imagen = file.getAbsolutePath();
    
answered by 08.03.2017 / 22:09
source