Error when multiplying java null values

Asked

Viewed 147 times

0

I’m having the following problem: In my project there are two fields (editText) where the user can or cannot enter the value.

Edittext that receives the amount etCount.

Edittext that receives the value etPriceUnit.

When the etCount and the etPriceUnit present the value "null" at the time of calculating the application closes.

This probably occurs in the attempt to convert to double and multiply null values on the line double doubleTOTAL_PRICE_ITEM = (Double.parseDouble(stringCOUNT) * Double.parseDouble(stringPRICE_UNIT));.

I tried the following to fix such problem:

if (stringCOUNT == null || stringPRICE_UNIT == null) {
    String stringTOTAL_PRICE_ITEM = "0";
} else {
    Double doubleTOTAL_PRICE_ITEM = (Double.parse.Double(stringCOUNT) * Double.parseDouble(stringPRICE_UNIT));
    String stringTOTAL_PRICE_ITEM = Double.toString(doubleTOTAL_PRICE_ITEM);
}

But I did not succeed. I cannot use the variable created within the if on the line result = crud.insertProduct(stringPRODUCT_NAME, stringCOUNT, stringPRICE_UNIT, stringTOTAL_PRICE_ITEM);.

Insertproduct.class (onClick):

public void onClick(View v) {

    Controller crud = new Controller(getBaseContext());
    EditText PRODUCT_NAME = (EditText) findViewById(R.id.etProductName);
    EditText COUNT = (EditText) findViewById(R.id.etCount);
    EditText PRICE_UNIT = (EditText) findViewById(R.id.etPriceUnit);

    String stringPRODUCT_NAME = PRODUCT_NAME.getText().toString();
    String stringCOUNT = COUNT.getText().toString();
    String stringPRICE_UNIT = PRICE_UNIT.getText().toString();
    double doubleTOTAL_PRICE_ITEM = (Double.parseDouble(stringCOUNT) * Double.parseDouble(stringPRICE_UNIT));
    String stringTOTAL_PRICE_ITEM = Double.toString(doubleTOTAL_PRICE_ITEM);
    String result;
    if (stringPRODUCT_NAME.matches("")) {
        Toast.makeText(InsertProduct.this, "Você não inseriu o nome do produto.", Toast.LENGTH_SHORT).show();
        return;
    }

    result = crud.insertProduct(stringPRODUCT_NAME, stringCOUNT, stringPRICE_UNIT, stringTOTAL_PRICE_ITEM);
    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();

    Intent intent = new Intent(InsertProduct.this, Main.class);
    startActivity(intent);
    finish();
}  

Controller.class (String insertProduct):

public String insertProduct(String PRODUCT_NAME, String stringCOUNT, String stringPRICE_UNIT, String stringTOTAL_PRICE_ITEM) {

    ContentValues values;
    long result;

    db = database.getWritableDatabase();
    values = new ContentValues();
    values.put(CreateDB.PRODUCT_NAME, PRODUCT_NAME);
    values.put(CreateDB.COUNT, stringCOUNT);
    values.put(CreateDB.PRICE_UNIT, stringPRICE_UNIT);
    values.put(CreateDB.TOTAL_PRICE_ITEM, stringTOTAL_PRICE_ITEM);

    result = db.insert(CreateDB.TABLE, null, values);
    db.close();

    if (result == -1)
        return "Erro ao inserir o produto.";
    else
        return "Produto inserido com sucesso!";
}

@Update Problem solved. Follows the solution.

String stringCOUNT = COUNT.getText().toString(); //Pegando o valor do etCount e convertendo para string
String stringPRICE_UNIT = PRICE_UNIT.getText().toString();

if (stringCOUNT.matches("")) { //Se o EditText estiver vazio faça
    doubleCOUNT = 0; //Atribui o valor 0 se o EditText estiver vazio
} else { //Senão
    doubleCOUNT = Double.parseDouble(stringCOUNT); //Pega o valor do EditText e converte para double
}

if (stringPRICE_UNIT.matches("")) {
    doublePRICE_UNIT = 0;
} else {
    doublePRICE_UNIT = Double.parseDouble(stringPRICE_UNIT);
}
  • 1

    have already tried to initialize the value of these variables as 0? so that if they are not modified they remain 0?

  • @Dolls symphooroso Olhá, I had not thought about it, I’m too lay. Could you tell me where I can declare the variable with value 0?

  • first it seems wrong to me that you try to perform mathematical operations with two strings, declare stringCOUNT and stringPRICE_UNIT as int or double.

  • To declare them with the value 0 do the following double stringCOUNT = 0 and double stringPRICE_UNIT = 0

  • @I declare the variables in the public class InsertProduct, in function onCreate() or in function onClick()?

  • etCount and etPriceUnit are two correct Edittexts?

  • Correct, I have already made the appropriate conversions declared in public class the following variables double doubleCOUNT = 0; and double doublePRICE_UNIT = 0;, and converted to double in function onClick() doubleCOUNT = Double.parseDouble(COUNT.getText().toString()); and doublePRICE_UNIT = Double.parseDouble(PRICE_UNIT.getText().toString());

  • I made a response to facilitate your understanding and abbreviate your code

Show 3 more comments

1 answer

3


Well to solve your problem I will give you a way to set the value 0 both to variable doubleCOUNT for the variable doublePRICE_UNIT when editText has nothing written.

Add the method addTextChangedListener() for your two editTexts (etCount and etPriceUnit) and do the following:

etCount:

etCount.addTextChangedListener(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) {

        if (s.length()>0){ //essa condição só executará se o editText não estiver vazio e fará com que seja adicionado o valor digitado no editText à variável doubleCOUNT

            doubleCOUNT=Double.parseDouble(etCount.getText().toString().trim());

        }else{ //essa condição fará com que seja atribuído o valor 0 à variável doubleCOUNT se não tiver nada escrito no editText (etCount)

            doubleCount=0;
            etCount.setHint("0");

        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

Just do the same thing with etPriceUnit.

Remembering that you cannot (at least not for what you are trying to do), multiply strings, because STRINGS variables are not only prepared to receive numbers, but also letters and special digits.

  • My friend, I don’t know how to thank you, it worked out! Thank you very much, you saved my week. Just one more thing the multiplication value of the doubleCOUNT * doublePRICE_UNIT is returning an extra number, unnecessary, type 1.5 * 1.39 = 2.085. I only need 2.08.

  • 1

    @Giovanirodrigo when applying setText to textView you do the following textView.setText(String.format("%.2f", x/y)); when you give the . format "point format" will appear two options, use the one that appears Locale l, String format, Object... args. The expression x/y was an expression used as an example, in its code vc subtitui by its.

  • x/y would be what exactly? The variable that holds the value 2.085?

  • nn, x/y was the expression ki I used as an example, you substitute for doubleCOUNT * doublePRICE_UNIT

  • These values are displayed through this code String[] field = new String[]{CreateDB.ID, CreateDB.PRODUCT_NAME, CreateDB.COUNT, CreateDB.PRICE_UNIT, CreateDB.TOTAL_PRICE_ITEM}; 
int[] idViews = new int[]{R.id.tvId, R.id.tvProductName, R.id.tvCount, R.id.tvPriceUnit, R.id.tvTotalPriceItem};

  • x/y in the case would be a variable dividing another. If you created a variable to store the multiplication value between doubleCOUNT and doublePRICE_UNIT you do the same thing => textView.setText(String.format("%.2f", variavelResultado))

  • One more error, if I add the item without the value, it works perfectly, if I add the item with value, the code transforms the value to 0.

  • you must have put to turn to 0 in one of the two scopes

  • I declared the variable as follows double doubleCOUNT= 0; and the doublePRICE_UNIT in the same way. But I declared them in public class and not at the event onCreate or in the onClick

Show 4 more comments

Browser other questions tagged

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