How to capture image from the camera of the mobile and send it to the server via rest using the volley?

3

I'm developing a MOBILE application that communicates with my web application, the application developed in Android Studio, and the web in PlayFramework . I created a form in APK that already consumes the service via rest using volleyball, everything already working, but only need to send the image along with the other fields of the form. As I am now learning how to create and consume services, I am having difficulty sending the image captured by the mobile phone on the form. Can someone help me.

My forms class in AS:

public class DenunciaActivity extends Activity implements AdapterView.OnItemSelectedListener, LocationListener {

double latitude = 0;
double longitude = 0;
public static final String TAG = "LOG";
//public static final String REGISTER_URL = "http://10.112.3.154:9000/Services/denuncia";
public static final String REGISTER_URL = "http://192.168.0.103:9000/Services/denuncia";
EditText femail, frua, fbairro, fcompl, fcidade, festado, fpais, fobs;
public String name;
public static final String KEY_USERNAME = "nome";
public static final String KEY_ADDRESS = "rua";
public static final String KEY_DISTRICT = "bairro";
public static final String KEY_COMPLEMENT = "complemento";
public static final String KEY_CITY = "cidade";
public static final String KEY_STATE = "estado";
public static final String KEY_NOTE = "observacao";
public static final String KEY_DATE = "data";
public static final String KEY_EMAIL = "email";
public static final String KEY_LAT = "latitude";
public static final String KEY_LONG = "longitude";
public static final String KEY_COUNTRIE = "pais";
public static final String KEY_STATUS = "status";
SimpleDateFormat formataData = new SimpleDateFormat("dd/MM/yyyy");
Date data = new Date();
String dataFormatada = formataData.format(data);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_denuncia );
    FacebookSdk.sdkInitialize(this);
    readMyCurrentCoordinates();
    Bundle inBundle = getIntent().getExtras();
    name = inBundle.get("name").toString();
    frua = (EditText) findViewById(R.id.rua);
    fbairro = (EditText) findViewById(R.id.bairro);
    fcompl = (EditText) findViewById(R.id.complemento);
    fcidade = (EditText) findViewById(R.id.cidade);
    festado = (EditText) findViewById(R.id.estado);
    fpais = (EditText) findViewById(R.id.pais);
    fobs = (EditText) findViewById(R.id.observacao);
    femail = (EditText) findViewById(R.id.email);

        EditText nome = (EditText)findViewById(R.id.nome);
        nome.setText(name, TextView.BufferType.EDITABLE);
    Button enviar = (Button) findViewById( R.id.enviar );


    enviar.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(valid() == true){
                registerForms();
            }
        }
    } );


}
public void tirarFoto(View view){
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if(data != null){
        Bundle bundle = data.getExtras();
        if(bundle != null){
            Bitmap img = (Bitmap) bundle.get("data");
            Toast toast = Toast.makeText(getApplicationContext(), "Foto anexada", Toast.LENGTH_LONG);
            toast.show();
        }
    }
}

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

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {}

@Override
public void onNothingSelected(AdapterView<?> parent) {}
public void registerForms() {

    final String address = frua.getText().toString().trim();
    final String district = fbairro.getText().toString().trim();
    final String city = fcidade.getText().toString().trim();
    final String email = femail.getText().toString().trim();
    final String complement = fcompl.getText().toString().trim();
    final String state = festado.getText().toString().trim();
    final String note = fobs.getText().toString().trim();
    final String countries = fpais.getText().toString().trim();


    StringRequest stringRequest = new StringRequest( Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            if (response.contains("Erro")) {
                Toast.makeText( DenunciaActivity.this, response, Toast.LENGTH_LONG ).show();

            } else {
                Intent intent = new Intent(DenunciaActivity.this, MainActivity.class);
                Toast.makeText( DenunciaActivity.this, response, Toast.LENGTH_LONG ).show();
                startActivity(intent);
            }

        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText( DenunciaActivity.this, error.toString(), Toast.LENGTH_LONG ).show();
                    Log.i( TAG, "Lat: " + error );
                }
            } ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> map = new HashMap<String, String>();
            map.put( KEY_USERNAME, name );
            map.put( KEY_DATE, dataFormatada );
            map.put( KEY_STATE, state );
            map.put( KEY_CITY, city );
            map.put( KEY_DISTRICT, district );
            map.put( KEY_ADDRESS, address );
            map.put( KEY_EMAIL, email );
            map.put( KEY_COMPLEMENT, complement );
            map.put( KEY_COUNTRIE, countries );
            map.put( KEY_LAT, String.valueOf( latitude ) );
            map.put( KEY_LONG, String.valueOf( longitude ) );
            map.put( KEY_NOTE, note );
            map.put( KEY_STATUS, "ATIVO" );
            Log.i( TAG, "Lat: " + longitude +" "+latitude);
            return map;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue( this );
    requestQueue.add( stringRequest );
}

}

On the other hand, my service:

public class Services extends Controller {
public static void denuncia(@Valid String nome, String data, String rua, String bairro, String complemento, String cidade, String estado, String pais, String observacao, String email, String latitude, String longitude, Status status) {
    if (validation.hasErrors()) {
        String mensagem = "Erro ao cadastrar";
        JsonObject j = new JsonObject();
        j.addProperty("Erro", 404);
        j.addProperty("msg", mensagem);
        renderJSON(j);
    } else {
        String msgsucess = "Cadastrado com sucesso!";
        Denuncia denuncia = new Denuncia();
        denuncia.nome = nome;
        denuncia.data = data;
        denuncia.rua = rua;
        denuncia.bairro = bairro;
        denuncia.complemento = complemento;
        denuncia.cidade = cidade;
        denuncia.estado = estado;
        denuncia.pais = pais;
        denuncia.observacao = observacao;
        denuncia.email = email;
        denuncia.latitude = latitude;
        denuncia.longitude = longitude;
        denuncia.status = status;
        denuncia.save();
        JsonObject j = new JsonObject();
        j.addProperty("Success", 200);
        j.addProperty("msg", msgsucess);
        renderJSON(j);
    }
}
}
    
asked by anonymous 31.12.2017 / 15:27

1 answer

2

Here is code that I use in one of my legacy applications, but it solves your problem. You'll put it together in the onActivityResult:

Bitmap img = (Bitmap)data.getExtras().get("data");

ByteArrayOutputStream stream = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.JPEG, 100, stream);
String foto = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);

Just be careful with the size of the request, many web servers limit the size of the request.

    
04.01.2018 / 11:26