Error in the monetary mask, saved with the correct digits but at the time of display are missing 2 digits

3

Colleagues!WhenIsavetheproductitgetsthecorrectdigitsasinthescreenabove.However,whenIentertheproductlistandclickontheScissorsproductitopensintheregistrationscreenwithtwodigitsmissingasinthescreenbelow.Anyonehaveanysuggestions?IasktobeasspecificaspossiblebecauseIdonothavemuchexperience.Thanksinadvancetoanyonewhocanhelp.Thankyou.

MyClassProductMaster:

importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.content.DialogInterface;importandroid.content.Intent;importandroid.graphics.Bitmap;importandroid.os.Bundle;importandroid.text.Editable;importandroid.text.TextWatcher;importandroid.view.View;importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.ImageView;importandroid.widget.Toast;importbr.gestaoBd.BancoDeDados.ProdutoDao;importbr.gestaoBd.Beans.Produto;importjava.text.NumberFormat;importjava.util.Locale;publicclassCadProdutosextendsActivity{privateImageViewimgView=null;staticfinalintSALVAR=0,EXCLUIR=1,LIMPAR=2;EditTextedId,edDescricao,edPrecoDeCusto,edPercDeLucro,edPrecoDeVenda;ProdutoDaoprodDao;Produtoproduto;@OverridepublicvoidonCreate(Bundleicicle){super.onCreate(icicle);setContentView(R.layout.cad_produtos);edId=(EditText)findViewById(R.id.cadEdId);edDescricao=(EditText)findViewById(R.id.cadEdDescricao);edPrecoDeCusto=(EditText)findViewById(R.id.cadEdPrecoDeCusto);edPrecoDeCusto.addTextChangedListener(newMonetaryMask(edPrecoDeCusto));edPercDeLucro=(EditText)findViewById(R.id.cadEdPercDeLucro);edPrecoDeVenda=(EditText)findViewById(R.id.cadEdPrecoDeVenda);edPrecoDeVenda.addTextChangedListener(newMonetaryMask(edPrecoDeVenda));imgView=(ImageView)findViewById(R.id.imgFoto);ProdutoprodutoRecebido=(Produto)getIntent().getSerializableExtra("Produto");
    if (produtoRecebido != null) {
        montaTela(produtoRecebido);
    } else {
        montaTela(new Produto());
    }

    Button btn1Salvar = (Button) findViewById(R.id.btSalvar);
    btn1Salvar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Produto pro = new Produto();
            pro.setId(Integer.valueOf(edId.getText().toString()));
            pro.setDescricao(edDescricao.getText().toString());
            pro.setPrecoDeCusto(MonetaryMask.stringMonetarioToDouble(edPrecoDeCusto.getText().toString()));
            pro.setPercDeLucro(Double.valueOf(edPercDeLucro.getText().toString()));
            pro.setPrecoDeVenda(MonetaryMask.stringMonetarioToDouble(edPrecoDeVenda.getText().toString()));

            if (pro.getId() > 0) {
                getProDao().alterar(pro);
            } else {
                getProDao().inserirProduto(pro);
            }
            ToastManager.show(getBaseContext(), "Salvo com Sucesso",
                    ToastManager.INFORMATION);

        }
    });

    Button btnLimpar = (Button) findViewById(R.id.btLimpar);

    btnLimpar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            montaTela(new Produto());
        }
    });

    Button bt2Excluir = (Button) findViewById(R.id.bt2Excluir);
    bt2Excluir.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final Produto pro = new Produto();
            pro.setId(Integer.valueOf(edId.getText().toString()));
            pro.setDescricao(edDescricao.getText().toString());
            pro.setPrecoDeCusto(Double.valueOf(edPrecoDeCusto.getText().toString()));
            pro.setPercDeLucro(Double.valueOf(edPercDeLucro.getText().toString()));
            pro.setPrecoDeVenda(Double.valueOf(edPrecoDeVenda.getText().toString()));

            AlertDialog.Builder builder = new AlertDialog.Builder(CadProdutos.this);
            builder.setTitle("Deseja Excluir?");
            builder.setMessage("O produto será deletado!");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    getProDao().excluir(pro);
                    montaTela(new Produto());
                    ToastManager.show(getBaseContext(), "Produto Excluído",
                            ToastManager.INFORMATION);

                }

            });

            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(CadProdutos.this, "Cancelado", Toast.LENGTH_LONG).show();
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

        }
    });
}

private void montaTela(Produto produto) {
    edId.setText(String.valueOf(produto.getId()));
    edDescricao.setText(produto.getDescricao());
    edPrecoDeCusto.setText(String.valueOf(produto.getPrecoDeCusto()));
    edPercDeLucro.setText(String.valueOf(produto.getPercDeLucro()));
    edPrecoDeVenda.setText(String.valueOf(produto.getPrecoDeVenda()));


}

public ProdutoDao getProDao() {
    if (prodDao == null) {
        prodDao = new ProdutoDao();
    }
    return prodDao;
}

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (data != null) {
        Bundle bundle = data.getExtras();

        if (bundle != null) {

            Bitmap bitmap = (Bitmap) bundle.get("data");


            imgView.setImageBitmap(bitmap);
        }
    }
}
} 

My Class Monetary Mask

 import android.text.Editable;
 import android.text.TextWatcher;
 import android.widget.EditText;
 import java.text.NumberFormat;

 public class MonetaryMask implements TextWatcher {

final EditText campo;

public static double stringMonetarioToDouble(String str) {
    double retorno = 0;
    try {
        boolean hasMask = ((str.indexOf("R$") > -1 || str.indexOf("$") > -1) && (str
                .indexOf(".") > -1 || str.indexOf(",") > -1));
        if (hasMask) {
            str = str.replaceAll("[R$]", "").replaceAll("\,\w+", "")
                    .replaceAll("\.\w+", "");
        }

        retorno = Double.parseDouble(str);
    } catch (NumberFormatException e) {

    }
    return retorno;
}

public MonetaryMask(EditText campo) {
    super();
    this.campo = campo;
}

private boolean isUpdating = false;

private NumberFormat nf = NumberFormat.getCurrencyInstance();

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

    if (isUpdating) {
        isUpdating = false;
        return;
    }

    isUpdating = true;
    String str = s.toString();

    boolean hasMask = ((str.indexOf("R$") > -1 || str.indexOf("$") > -1)
            && (str.indexOf(".") > -1 || str.indexOf(",") > -1));

    if (hasMask) {

        str = str.replaceAll("[R$]", "").replaceAll("[,]", "")
                .replaceAll("[.]", "");
    }

    try {

        str = nf.format(Double.parseDouble(str) / 100);
        campo.setText(str);
        campo.setSelection(campo.getText().length());
    } catch (NumberFormatException e) {
        s = "";
    }
}

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

}

@Override
public void afterTextChanged(Editable s) {

}

}
    
asked by anonymous 09.01.2016 / 16:53

1 answer

3

The problem is in the static method stringMonetarioToDouble(String) : it loses information when converting the String and returns erroneously to the persistence layer that retrieves a Produto displays incorrect values. Some examples:

  

"R $ 0.10" = 0.0

     

"$ 0.01" = 0.0

     

"$ 1.00" = 1.0

     

"$ 10.00" = 10.0

     

"$ 10.00" = 10.0

     

"$ 10.50" = 10.0

An output would be in the MonetaryMask class to save the original input from the user and add a method that would return the double value based on the original rather than the "masked" value. For example:

public class MonetaryMask implements TextWatcher {

    // ...

    private String mRawInput;

    // ...

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

        // ...

        mRawInput = new String(s.toString());

        String str = s.toString();

        // ...
    }

    public double getMonetarioAsDouble() {
        if (mRawInput == null) {
            return 0.0d;
        }

        return Double.parseDouble(mRawInput) / 100.0d;
    }
}

In this way, you should save the instances of MonetaryMask used. As in this section:

    private MonetaryMask mPrecoDeCustoMonetaryMask;

    // ...

    mPrecoDeCustoMonetaryMask = new MonetaryMask(edPrecoDeCusto);

    edPrecoDeCusto.addTextChangedListener(mPrecoDeCustoMonetaryMask);

    // ...

And before persisting, use the method getMonetarioAsDouble() of the instance to save the fields in Produto :

    pro.setPrecoDeCusto(mPrecoDeCustoMonetaryMask.getMonetarioAsDouble());

Another point is that when you retrieve Produto you need to transform the double value into the entry that the user inserts into the mask. For example, if the user entered "100" is masked as "$ 1.00", but is persisted as 1.00 and needs to turn "100" to be set to EditText . It might look something like this:

    private void montaTela(Produto produto) {

        // ...

        edPrecoDeCusto.setText(String.valueOf(produto.getPrecoDeCusto() * 100.0d)));

        // ... 
    }

I hope I have helped.

    
21.01.2016 / 04:00