Problem while saving file on Android Lolipop from second generation moto-g

Asked

Viewed 117 times

0

Good morning, I have an app that works normally on all versions of Android from-the 2 to the first generation moto-g version, this app is very simple, I describe the details I need to add in the photo name, I take the photo and it saves the photo with the information I described, today when trying to use it in a motorcycle-g second generation the application does the whole process as if everything is happening correctly but when I go in my files the folder is not there, I did a debugging and realized that it fails to create the folder "DBQ_LTQ" folder where saved the photos, it creates and deletes at the same instant tried to create manual and gave the same problem, I tried then to change the directory and save on the main page of the internal memory with another name and the error persists, uninstalled the application and the folder appeared without any file, follow the code below:

/**
 *  Matheus Henrique Rodrigues de Arruda @ Aperam Inox America do Sul S/A.
 */
package info.androidhive.androidcameraapi;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
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.text.InputFilter;
import matheus.arruda.msinfo.dev.com.*;
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 = "AperamApps/Foto-PLQA";

    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);
        txtum.setFilters(new InputFilter[] {new InputFilter.AllCaps()});



        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 if ( spinlado.getSelectedItem().equals("Selecione:")) {
                    Toast.makeText(getApplicationContext(),
                            "ATENÇÃO: - O campo Defeito é de preenchimento obrigatório.",
                            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.getExternalStorageDirectory(),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
                    + unidademetalica + " Defeito_" + lado + " Outros_ " + outrasinformacoes + " Data_ " + timeStamp + ".jpg");        



        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                     + unidademetalica + " Defeito_" + lado + " Outros_ " + outrasinformacoes + " Data_ " + timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;


    }


}
  • Does the App stop? Check the error that is emitted in LOG Cat and post here.

  • This version has new security implementations, already checked the documentation?

  • Good morning, the application does not lock, it works as if everything went well, in debugging I realized that the application does not lock because it creates the folder and the file, only that soon after the folder and the file is deleted. @rubStack, I haven’t read it yet.

  • Take a look at the documentation of the method you are using, as @rubStackOverflow said, new security features have been added to this release.

No answers

Browser other questions tagged

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