Problem saving camera image to server

Asked

Viewed 58 times

1

Come on, guys, I’m having a problem saving a camera image on the server. I put a standard image in my Image View and this image is clickable, triggering the android camera. When the photo is taken, it goes to Image View all right, however, when I send save the image that is saved is the default image that was previously in Image View.

Java class:

public class FormProductActivity extends AppCompatActivity {

private Spinner spTypeProduct;
private EditText inputNameProduct, inputPriceProduct;
private String strPrice, compareValue, productName, productType, localFile, strBakeryId, strImage;
private Double productPrice;
private Resources resources;
private Button btnAddProduct;
public static final String APP_NAME = "PanApp";
private static final String TAG = FormProductActivity.class.getSimpleName();
public static final String URL = "https://panapp-backend.appspot.com/_ah/api";
private ProgressDialog progressDialog;
private Long bakeryId;
private Product product;
private ImageView imageProduct;
private ArrayAdapter<String> dataAdapter;
private static final int MAKE_PHOTO = 1888;
//private ImageHelper imageHelper;
private byte[] image;
private Bundle params;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent it = getIntent();
    params = it.getExtras();
    if (params != null) {
        bakeryId = params.getLong("bakeryId");
    }

    setContentView(R.layout.activity_form_product);
    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            callClearErrors(s);
        }
    };
    resources = getResources();
    imageProduct = (ImageView) findViewById(R.id.img_product);
    imageProduct.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*localFile = Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + ".jpg";
            File file = new File(localFile);
            Uri localPhoto =  Uri.fromFile(file);
            Intent goCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            goCamera.putExtra(MediaStore.EXTRA_OUTPUT, localPhoto);

            startActivityForResult(goCamera, MAKE_PHOTO);*/

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, MAKE_PHOTO);
        }
    });

    inputNameProduct = (EditText) findViewById(R.id.et_product_name);
    inputNameProduct.addTextChangedListener(textWatcher);
    inputPriceProduct = (EditText) findViewById(R.id.et_product_price);
    spTypeProduct = (Spinner) findViewById(R.id.sp_product_type);
    btnAddProduct = (Button) findViewById(R.id.btn_save_product);
    List<String> categories = new ArrayList<String>();
    categories.add("Pães");
    categories.add("Bolos");
    categories.add("Cucas");
    categories.add("Bebidas");
    categories.add("Salgados");
    categories.add("Doces");
    categories.add("Frios");
    categories.add("Biscoitos");
    categories.add("Outros");
    dataAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, categories);
    spTypeProduct.setAdapter(dataAdapter);
    spTypeProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            productType = parent.getItemAtPosition(position).toString();
        }

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

        }
    });
    btnAddProduct.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validateFields()) {
                progressDialog = ProgressDialog.show(FormProductActivity.this, "Salvando produto...", "Aguarde um momento", true, false);

                new AsyncTask<String, Void, Boolean>() {
                    @Override
                    protected Boolean doInBackground(String... params) {
                        String content = params[0];

                        ProductApi.Builder productBuilder = new ProductApi.Builder(AndroidHttp.newCompatibleTransport(),
                                new AndroidJsonFactory(), null).setRootUrl(URL);

                        productBuilder.setApplicationName(APP_NAME);
                        ProductApi productService = productBuilder.build();
                        product = new Product();

                        product.setProductName(productName);
                        product.setProductPrice(productPrice);
                        product.setType(productType);
                        product.setBakeryId(bakeryId);
                        //image = convertImageToByte(imageProduct);
                        //strImage = Base64.encodeToString(image, 0);
                        strPrice = productPrice.toString();
                        strBakeryId = bakeryId.toString();
                        product.setProductImage(strImage);

                        try {
                            productService.insert(product).execute();
                        } catch (IOException e) {
                            Log.e(TAG, e.getMessage(), e);
                            return false;
                        }
                        return true;
                    }

                    @Override
                    protected void onPostExecute(Boolean result) {
                        if (result) {
                            progressDialog.dismiss();
                            Toast.makeText(FormProductActivity.this, "Produto cadastrado com sucesso", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(FormProductActivity.this, "Erro ao enviar registro" + strImage, Toast.LENGTH_SHORT).show();
                            progressDialog.dismiss();
                        }
                    }
                }.execute(productName, strPrice, productType, strBakeryId, strImage);
            }
        }
    });

}

private void callClearErrors(Editable s) {
    if (!s.toString().isEmpty()) {
        clearErrorFields(inputNameProduct);
    }
}

private void clearErrorFields(EditText... editTexts) {
    for (EditText editText : editTexts) {
        editText.setError(null);
    }
}

private boolean validateFields() {
    productName = inputNameProduct.getText().toString().trim();
    productPrice = Double.valueOf(inputPriceProduct.getText().toString().trim());
    return (!isEmptyFields(productName, productPrice));
}

private boolean isEmptyFields(String name, Double price) {
    String priceAux = price.toString();
    if (TextUtils.isEmpty(name)) {
        inputNameProduct.requestFocus(); //seta o foco para o campo name
        inputNameProduct.setError(resources.getString(R.string.register_name_required));
        return true;
    } else if (TextUtils.isEmpty(priceAux)) {
        inputPriceProduct.requestFocus(); //seta o foco para o campo email
        inputPriceProduct.setError(resources.getString(R.string.price_product_required));
        return true;
    }
    return false;
}

public void loadPhoto(String localPhoto) {
    Bitmap imagePhoto = BitmapFactory.decodeFile(localPhoto);

    //Gerar imagem reduzida
    Bitmap reducedImagePhoto = Bitmap.createScaledBitmap(imagePhoto, 150, 200, true);

    product.setProductImage(localPhoto);

    imageProduct.setImageBitmap(reducedImagePhoto);
}

public void setProduct(Product product) {
    inputNameProduct.setText(product.getProductName());
    inputPriceProduct.setText(product.getProductPrice().toString());
    compareValue = product.getType();
    if (!compareValue.equals(null)) {
        int spinnerPostion = dataAdapter.getPosition(compareValue);
        spTypeProduct.setSelection(spinnerPostion);
        spinnerPostion = 0;
    }
    this.product = product;
    if (product.getProductImage() != null) {
        loadPhoto(product.getProductImage());
    }
}

public ImageView getPhoto() {
    return imageProduct;
}

public byte[] convertImageToByte(ImageView imageProduct) {

    Bitmap bitmap = ((BitmapDrawable) imageProduct.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
    image = stream.toByteArray();

    return image;
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MAKE_PHOTO && resultCode == RESULT_OK) {
        imageProduct = null;
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageProduct.setImageBitmap(photo);

        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            image = stream.toByteArray();
            strImage = Base64.encodeToString(image, 0);

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

    } else if (resultCode == RESULT_CANCELED) {//Cancelou a foto
        Toast.makeText(this, "Cancelou", Toast.LENGTH_SHORT).show();
    } else { //Saiu da Intent
        Toast.makeText(this, "Saiu", Toast.LENGTH_SHORT).show();
    }

}

}

XML file:

<?xml version="1.0" encoding="utf-8"?>

<ImageView
    android:id="@+id/img_product"
    android:layout_width="200sp"
    android:layout_height="150sp"
    android:src="@drawable/img_product"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<EditText
    android:paddingTop="8dp"
    android:id="@+id/et_product_name"
    android:hint="Nome do produto"
    android:layout_below="@+id/img_product"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textCapWords" />

<LinearLayout
    android:id="@+id/ll"
    android:layout_below="@id/et_product_name"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:text="R$: "
        android:textSize="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:paddingTop="8dp"
        android:id="@+id/et_product_price"
        android:hint="Preço do produto"
        android:layout_below="@+id/et_product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal" />
</LinearLayout>

<TextView
    android:paddingTop="8dp"
    android:text="Categoria"
    android:id="@+id/tv_categories"
    android:layout_below="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Spinner
    android:paddingTop="8dp"
    android:id="@+id/sp_product_type"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tv_categories">

</Spinner>

<Button
    android:paddingTop="12dp"
    android:text="Gravar"
    android:textColor="#ffffff"
    android:id="@+id/btn_save_product"
    android:layout_below="@+id/sp_product_type"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#3498db"/>

If you can help, thank you.

  • rpz, you already tried to print this image, there on onActivityResult and before saving to see if they are the same thing?

  • Yes, I put a print and gave the same binary always. Dai uninstalled and installed the apk again and it worked. Now another question, I need to save the photo in mobile memory? You have how to do without saving this image?

No answers

Browser other questions tagged

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