Using Android Camera

1

Good afternoon guys, I'm new here, so I'm sorry to ask you anything already commented on. Next we have an app in the company already a while ago for sdk 7, what happens is that they recently requested to use the camera for photos, well I'm using the camera try as below:

    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

    startActivityForResult(intent, 123);

and taking the result usually as below:

     protected void onActivityResult(int requestCode, int resultCode, Intent data) {

      if (requestCode == 123) {
         if (resultCode == Activity.RESULT_OK) {

            Uri image = getLastImage();
            String caminho = getRealPathFromURI(image);

            Bitmap bitmap = BitmapFactory.decodeFile(caminho);


            // Chame este método pra obter a URI da imagem
            Uri uri = getImageUri(getApplicationContext(), bitmap);

            // Em seguida chame este método para obter o caminho do arquivo
            File file = new File(getRealPathFromURI(uri));




             System.out.println("Caminho - "+file.getPath());

        } else {
            Toast.makeText(this, "Imagem não enviada", Toast.LENGTH_LONG)
                    .show();

        }

    } else {
        Toast.makeText(this, "Request não confere", Toast.LENGTH_LONG)
                .show();

    }

    private Uri getLastImage() {
    final ContentResolver cr = getContentResolver();
    final String[] p1 = new String[] { MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATE_TAKEN };
    Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1,
            null, null, p1[1] + " DESC");

    int imageID = 0;
    if (c1.moveToFirst()) {
        imageID = c1.getInt(0);
    }
    c1.close();
    Uri uri = Uri.withAppendedPath(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            Integer.toString(imageID));
    return uri;
}

private void Sleep(int i) {
    // TODO Auto-generated method stub

}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(),
            inImage, "50609", "drawing");
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

But unfortunately it is not working very well on some devices, I tested on two android 4.1.2 being LG and Samsung, I also tested on a G2 bike with android 6.0 and it worked, but on another G3 motorcycle with the same OS, neither it nor us asus with 5.0.0 simply open the camera but at the time of recording hangs the cell phones (unfortunately the phones that gave problem I do not have here for error testing) so I realized how the camera opens the impression of lack of permission to write, I already tried several methods seen in google without success, someone already had this kind of problem, alias I have tried in several ways to get the result by data.getData (), or data.getExtras ("data") being that the first returns null in the versions of android and the second lock. if anyone has any ideas that might help me.

Follow my manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tirarfoto"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="7" />

<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.CAMERA" android:maxSdkVersion="22" android:required="true"/>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="22" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="22" android:required="true" />

<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera" android:required="false" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:exported="true" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

    
asked by anonymous 10.08.2016 / 18:59

2 answers

2

I create the Intent for camera by passing the path where I want it to save the photo, so I already have the photo that was taken saved in that location.

void tirarFoto(){
    File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

    SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
    String nomeFoto = s.format(new Date());
    nomeFoto = codigo + nomeFoto + ".jpg";

    File file = new File(imagesFolder, nomeFoto);
    mCurrentPhotoPath = file.getAbsolutePath();//variavel global
    Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    mTipoFoto = tipofoto;
    startActivityForResult(imageIntent, CAMERA_ACTIVITY_REQUEST_CODE);
}

When I get the result of the camera I take the picture taken from the global variable that I saved the way before.

@OnActivityResult(CAMERA_ACTIVITY_REQUEST_CODE)
void onResult(int resultCode) {
    File file = new File(mCurrentPhotoPath);
    switch (resultCode) {
        case RESULT_OK:
        // salvar foto
        break;
        case RESULT_CANCELED:
            //deletar a foto
            break;
        default:
            //deletar a foto
    }
}

If it cancels and does not take the photo I delete the created file.

I hope I have helped.

    
11.08.2016 / 15:52
1

I have already solved the problem, followed some tips from Edileuson Dias, I will post the complete process if anyone needs it is easy to use.

I made this test application for another so I might have some flaws that I fixed at the time of transporting to my main, but this worked.

I am taking photos by compressing and sending via FTP follows:

FTP class

  import java.io.FileInputStream;

  import org.apache.commons.net.ftp.FTP;
  import org.apache.commons.net.ftp.FTPClient;

  import android.os.AsyncTask;
  import android.util.Log;


    public class Envio extends AsyncTask<String, Integer, Boolean> {
    private FTPClient ftp;
    private Object sistema;
    private String numero;
    private String longitude;
    private String latitude;
    private Boolean Erro;
    private String local;
    private String caminho;

    @Override
    protected Boolean doInBackground(String... params) {

        sistema = params[0];
        numero = params[1];
        caminho = params[2];
        longitude = params[3];
        latitude = params[4];

        ftp = new FTPClient();

        if (sistema.equals("1")) {
            local = "se precicar colocar em pasta diferente";
        }
        if (sistema.equals("2")) {
            local = "se precicar colocar em pasta diferente";
        }

        try {

            String diretorio = caminho;
            String nomeArquivo = numero + ".jpg";
            ftp.connect("www.seuendereco.com.br", 21);
            ftp.login("login", "senha");
            ftp.changeWorkingDirectory("/imagens/" + local);
            FileInputStream arqEnviar = new FileInputStream(diretorio);

            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.storeFile(nomeArquivo + "_" + latitude + "_" + longitude,
                    arqEnviar);
            ftp.logout();
            ftp.disconnect();
            Log.d("AMEE LD", "enviado com sucesso");
            Erro = true;

        } catch (Exception e) {
            Erro = false;
        }

        return Erro;
    }
 }

Class to create Database

   import android.content.Context;
   import android.database.sqlite.SQLiteDatabase;
   import android.database.sqlite.SQLiteOpenHelper;

    public class CriaBanco extends SQLiteOpenHelper {

    private static final String NOME_BANCO = "imagem.db";
    private static final Integer ID = 0;
    private static final String TIPO = "tipo";
    private static final String NUMERO_OS = "numero_os";
    private static final String END_IMAGEM = "end_imagem";
    private static final String LONGITUDE = "longitude";
    private static final String LATITUDE = "latitude";

    private static final String TABELA = "IMAGEM";
    private static final int VERSAO = 1;

    public CriaBanco(Context context) {
        super(context, NOME_BANCO, null, VERSAO);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String sql = "CREATE TABLE " + TABELA + "("
                + "id integer primary key autoincrement,"
                + TIPO  + " text,"
                + NUMERO_OS + " text,"
                + END_IMAGEM + " text,"
                + LONGITUDE + " text,"
                + LATITUDE + " text )";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS" + TABELA);
        onCreate(db);
    }

    public static String getNomeBanco() {
        return NOME_BANCO;
    }

    public static Integer getId() {
        return ID;
    }

    public static String getTipo() {
        return TIPO;
    }

    public static String getNumeroOs() {
        return NUMERO_OS;
    }

    public static String getEndImagem() {
        return END_IMAGEM;
    }


    public static String getLongitude() {
        return LONGITUDE;
    }

    public static String getLatitude() {
        return LATITUDE;
    }

    public static String getTabela() {
        return TABELA;
    }

    public static int getVersao() {
        return VERSAO;
    }

    }

Connection to the bank

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;

    import com.example.conexao.CriaBanco;

    public class BancoController {
    private SQLiteDatabase db;
    private CriaBanco banco;

    public BancoController(Context context) {
        banco = new CriaBanco(context);
    }

    public String insereDado(String tipo, String numero_os, String end_imagem,
            String longitude, String latitude) {
        ContentValues valores;
        long resultado;

        db = banco.getWritableDatabase();
        valores = new ContentValues();
        valores.put(CriaBanco.getTipo(), tipo);
        valores.put(CriaBanco.getNumeroOs(), numero_os);
        valores.put(CriaBanco.getEndImagem(), end_imagem);
        valores.put(CriaBanco.getLongitude(), longitude);
        valores.put(CriaBanco.getLatitude(), latitude);

        resultado = db.insert("IMAGEM", null, valores);
        db.close();

        if (resultado == -1)
            return "Erro ao inserir registro";
        else
            return "Registro Inserido com sucesso";

    }

    public Cursor carregaDados() {
        Cursor cursor;
        String[] campos = { CriaBanco.getTipo(), CriaBanco.getNumeroOs(),
                CriaBanco.getEndImagem(), CriaBanco.getLongitude(),
                CriaBanco.getLatitude() };
        db = banco.getReadableDatabase();
        cursor = db.query(CriaBanco.getTabela(), campos, null, null, null,
                null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        db.close();
        return cursor;
    }

    public Cursor carregaDadoById(int id) {
        Cursor cursor;
        String[] campos = { CriaBanco.getTipo(), CriaBanco.getNumeroOs(),
                CriaBanco.getEndImagem(), CriaBanco.getLongitude(),
                CriaBanco.getLatitude() };
        String where = CriaBanco.getId() + "=" + id;
        db = banco.getReadableDatabase();
        cursor = db.query(CriaBanco.getTabela(), campos, where, null, null,
                null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        db.close();
        return cursor;
    }

    public String deletaRegistro(String numero_os) {
        long resultado;
        String where = CriaBanco.getNumeroOs() + "= '" + numero_os + "'";
        db = banco.getReadableDatabase();
        resultado = db.delete(CriaBanco.getTabela(), where, null);
        db.close();
        if (resultado == -1)
            return "Erro ao apagar registro";
        else
            return "Registro apagado com sucesso";
    }
   }

Class main

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


  @SuppressLint("NewApi")
  public class MainActivity extends ActionBarActivity {
  private ImageButton btCamera;
  private Button btler;
  private Button btdelete;
  private String numero_os1;
  private EditText numeroOs;
  private String Numero;
  private File tempFile;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Botao para Camera
    btCamera = (ImageButton) findViewById(R.id.btCamera);
    btCamera.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // prepara variavel para receber o numero do servico

            numeroOs = (EditText) findViewById(R.id.etNumeroServico);
            Numero = numeroOs.getText().toString();

            if (Numero.equals("")) {
                Toast.makeText(getApplicationContext(),
                        "Favor Inserir Numero", Toast.LENGTH_LONG).show();
            } else {
                tirar_foto();
            }

        }
    });

    // Botao para ler
    btler = (Button) findViewById(R.id.btler);
    btler.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // prepara variavel para receber o numero do servico

            BancoController read = new BancoController(getBaseContext());
            Cursor cursor = read.carregaDados();

            if (cursor.isAfterLast() == true) {
                Toast.makeText(getApplicationContext(),
                        "Nenhum Item a ser Enviado", Toast.LENGTH_LONG)
                        .show();
            } else {

                while (!cursor.isAfterLast()) {
                    String tipo = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getTipo())));
                    numero_os1 = (cursor.getString(cursor
                               .getColumnIndexOrThrow(CriaBanco.getNumeroOs())));
                    String end_imagem1 = (cursor.getString(cursor
                             .getColumnIndexOrThrow(CriaBanco.getEndImagem())));
                    String longitude = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getLongitude())));
                    String latitude = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getLatitude())));

                    System.out.println("TIPO - " + tipo);
                    System.out.println("numero_os - " + numero_os1);
                    System.out.println("tipo - " + tipo);
                    System.out.println("longitude - " + longitude);
                    System.out.println("latitude - " + latitude);

                    File file = new File(end_imagem1);
                    if (file.exists()) {
                        String Resultado = null;

                        try {
                            Boolean retorno = new Envio().execute(tipo,
                                    numero_os1, end_imagem1, longitude,
                                    latitude).get();

                            System.out.println("Retorno " + retorno);

                            if (retorno == true) {
                                Resultado = "Imagem enviada";
                            } else {
                                Resultado = "Imagem não enviada";
                            }

                        } catch (Exception ex) {
                            Resultado = "Imagem não enviada";
                            System.out.println(ex);
                        }
                        System.out.println("Imagem Enviada - Nº "
                                + numero_os1);

                        Toast.makeText(getApplicationContext(), Resultado
                                + " - Nº " + numero_os1, Toast.LENGTH_LONG);

                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Imagem não encontrada", Toast.LENGTH_LONG)
                                .show();
                    }
                    cursor.moveToNext();

                }

            }
        }
    });

    // Botao para delete
    btdelete = (Button) findViewById(R.id.btdelete);
    btdelete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // prepara variavel para receber o numero do servico

            BancoController read = new BancoController(getBaseContext());
            Cursor cursor = read.carregaDados();

            // chama classe controller do bd
            BancoController crud = new BancoController(getBaseContext());

            if (cursor.isAfterLast() == true) {
                Toast.makeText(getApplicationContext(),
                        "Nenhum Item a ser Apagado", Toast.LENGTH_LONG)
                        .show();
            } else {
                while (!cursor.isAfterLast()) {
                    String resultado;

                    numero_os1 = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getNumeroOs())));

                    String end_imagem1 = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getEndImagem())));

                    File file = new File(end_imagem1);
                    Boolean deleted = true;
                    if (file.exists()) {
                        try {
                            deleted = file.delete();
                        } catch (Exception e) {
                            deleted = false;
                            throw new RuntimeException(
                                    "Erro ao deletar imagem", e);
                        }

                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Imagem não encontrada", Toast.LENGTH_LONG)
                                .show();
                    }
                    if (deleted == true) {
                        resultado = crud.deletaRegistro(numero_os1);

                        Toast.makeText(getApplicationContext(),
                                resultado + " - Imagem - " + numero_os1,
                                Toast.LENGTH_LONG).show();
                    }

                    cursor.moveToNext();
                }

            }
        }
    });

}

public void tirar_foto() {

    File mediaStorage = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            "Camera");

    String nomeFoto = Numero + ".jpg";
    tempFile = new File(mediaStorage, nomeFoto);

    System.out.println("temp -" + tempFile);

    if (tempFile.exists()) {
        tempFile.delete();
    }
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));

    startActivityForResult(intent, 123);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent  data) {
    if (requestCode == 123) {
        if (resultCode == Activity.RESULT_OK) {
            String end_imagem = null;

            numeroOs = (EditText) findViewById(R.id.etNumeroServico);
            Numero = numeroOs.getText().toString();

            // variaveis para gravação
            String tipo = "1";// pos
            String numero_os = Numero;
            String longitude = "-25.4344087";
            String latitude = "-49.26725736";
            String resultado;

            File mediaStorage = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                    "Camera");

            String nomeFoto = Numero + ".jpg";
            tempFile = new File(mediaStorage, nomeFoto);

            end_imagem = tempFile.getPath();

            File cam_imagem = new File(end_imagem);

            if (cam_imagem.exists()) {
                Toast.makeText(getApplicationContext(), "existe",
                        Toast.LENGTH_LONG).show();
            }
            System.out.println("caminho - " + end_imagem);

            // busca imagem e comprime
            new BitmapFactory();
            Bitmap bitmap = BitmapFactory.decodeFile(end_imagem);

            // cria um stream pra salvar o arquivo
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(end_imagem);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // salva a imagem reduzida no disco
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);

            // chama classe controller do bd
            BancoController crud = new BancoController(getBaseContext());
            resultado = crud.insereDado(tipo, numero_os, end_imagem,
                    longitude, latitude);

            Toast.makeText(getApplicationContext(), resultado,
                    Toast.LENGTH_LONG).show();

        } else {
            Toast.makeText(this, "Imagem não enviada", Toast.LENGTH_LONG)
                    .show();

        }

    } else {
        Toast.makeText(this, "Request não confere", Toast.LENGTH_LONG)
                .show();
    }
}

public boolean verificaConexao() {
    boolean conectado;
    ConnectivityManager conectivtyManager = (ConnectivityManager)   getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conectivtyManager.getActiveNetworkInfo() != null
            && conectivtyManager.getActiveNetworkInfo().isAvailable()
            && conectivtyManager.getActiveNetworkInfo().isConnected()) {
        conectado = true;
    } else {
        conectado = false;
    }
    return conectado;
}

private void Sleep(int i) {
    // TODO Auto-generated method stub

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

layout

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<ImageButton
    android:id="@+id/btCamera"
    android:layout_width="37dp"
    android:layout_height="32dp"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="104dp"
    android:src="@drawable/cameras" />

<EditText
    android:id="@+id/etNumeroServico"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="24dp"
    android:ems="10"
    android:inputType="text" />

<Button
    android:id="@+id/btdelete"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/btler"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="56dp"
    android:text="Deletar" />

<Button
    android:id="@+id/btler"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/btdelete"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp"
    android:text="Ler/Enviar" />

only  I do not know how to close the question as resolved, if anyone can help me.

    
15.08.2016 / 18:51