Photo saved but not shown in the gallery

Asked

Viewed 1,297 times

1

Good evening, I’m with a design of a camera that adds in the name of the photo what the user writes in the text fields.

The app works only that the photo does not go to the gallery. Only appears in the gallery if I access the folder by PC, IE, it is saved however, to see it in the gallery I need to connect a USB cable to access the folder, then it appears.

Follow Activity /** *
*/ package info.androidhive.androidcameraapi;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import matheus.arruda.msinfo.dev.com.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.VideoView;
import android.app.AlertDialog;

public class MainActivity extends Activity {


    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    // Diretório para salvar
    private static final String IMAGE_DIRECTORY_NAME = "DBQ_LTQ";

    private Uri fileUri;

    public static  EditText txtum;
    public static  EditText txtoutros;
    private static Spinner spinlado;
    private Button btnCapturePicture, btnRecordVideo, sobrebtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtum = (EditText)findViewById(R.id.txtum);  
        txtoutros = (EditText)findViewById(R.id.txtoutros);  
        spinlado = (Spinner) findViewById(R.id.spinlado);
        btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
        btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
        sobrebtn = (Button) findViewById(R.id.sobrebtn);






        btnCapturePicture.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if(txtum.length()==0){
                    Toast.makeText(getApplicationContext(),
                            "ATENÇÃO: - O campo Unidade Metálica é de preenchimento obrigatório, favor preencher e tentar novamente.",
                            Toast.LENGTH_LONG).show();
                    }
                else {
                    captureImage();
                }

            }

        });


        btnRecordVideo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(txtum.length()==0){
                    Toast.makeText(getApplicationContext(),
                            "ATENÇÃO: - O campo Unidade Metálica é de preenchimento obrigatório, favor preencher e tentar novamente.",
                            Toast.LENGTH_LONG).show();
                    }
                else {
                    recordVideo();
                }
            }
        });



        sobrebtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                setContentView(R.layout.sobre);


                 new java.util.Timer().schedule( 
                        new java.util.TimerTask() {
                            @Override
                            public void run() {

                                Intent intent = getIntent();

                                startActivity(intent);
                            }
                        }, 
                        3000
                );
            }
        });



        // Checking camera availability
        if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "Erro (7002) Seu dispositivo não possui uma camera.",
                    Toast.LENGTH_LONG).show();
            // Fecha a activity caso o aparelho não possua camêra
            finish();
        }
    }

    /**
     * Verifica a compatibilidade do telefone
     * */
    private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {

            return true;
        } else {

            return false;
        }
    }


    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);


        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);


        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);


        fileUri = savedInstanceState.getParcelable("file_uri");

    }


    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);


        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 


        // inicia a camêra
        startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
    }


    /**
     * Receiving activity result method will be called after closing the camera
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                previewCapturedImage();
            } else if (resultCode == RESULT_CANCELED) {
                // Alertas
                Toast.makeText(getApplicationContext(),
                        "Você fechou a camera", Toast.LENGTH_SHORT)
                        .show();
            } else {

                Toast.makeText(getApplicationContext(),
                        "Desculpe! O aplicativo falhou.", Toast.LENGTH_SHORT)
                        .show();
            }
        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                previewVideo();
            } else if (resultCode == RESULT_CANCELED) {

                Toast.makeText(getApplicationContext(),
                        "Você cancelou a gravação do video", Toast.LENGTH_SHORT)
                        .show();
            } else {

                Toast.makeText(getApplicationContext(),
                        "Desculpe! O aplicativo falhou favor reiniciar a gravação", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }


    private void previewCapturedImage() {
        try {
            // // exibe um preview


            // gera mapa
            BitmapFactory.Options options = new BitmapFactory.Options();

            // ajusta o OutOfMemory do app a fim de evitar erros

            options.inSampleSize = 8;

            final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                    options);


        } catch (NullPointerException e) {
            e.printStackTrace();

        }
    }

    // exibe um preview
    private void previewVideo() {
        try {


        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /*
     * Cria o ID Uri da foto/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /*
     * Retorna com a foto/video
     */
    private static File getOutputMediaFile(int type) {

        // Seta o diretorio externo
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                IMAGE_DIRECTORY_NAME);

        // Cria diretoria
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(IMAGE_DIRECTORY_NAME, "Erro: (7001) Entre em contato com o administrador "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }




        String unidademetalica = ((String) txtum.getText().toString());
        String outrasinformacoes = ((String) txtoutros.getText().toString());
        String lado = spinlado.getSelectedItem().toString();


        // Cria arquivo

        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "UM_ " + unidademetalica + " Lado_" + lado + " Outros_ " + outrasinformacoes + " Data_ " + timeStamp + ".jpg");      



        } else if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "UM_ " + unidademetalica + " Lado_" + lado + " Outros_ " + outrasinformacoes + " Data_ " + timeStamp + ".mp4");      

        } else {
            return null;
        }

        return mediaFile;


    }


}
  • Matheus, after creating the file with the image or video, you need to notify the MediaStore to update its database. Some applications may consult the MediaStore instead of the physical folder of DCIM, your image will not appear.

  • Wakim, here’s the thing, if I just hit a photo with the current date and time it appears correctly in the gallery, but when the user adds information to the name gives this problem, it seems that the problem is that the image name gets too big, the funny thing is that accessing this folder by PC, it appears normally in the gallery.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.