简体   繁体   中英

How to convert double data in string to set on a textview on android studio

I am doing a simple calculator, the code:

public void calculate(View view){

    EditText txt11 = (EditText)findViewById(R.id.txt1);
    EditText txt22 = (EditText)findViewById(R.id.text2);
    TextView result = (TextView)findViewById(R.id.resultado);

    Button btn = (Button)findViewById(R.id.button);

    double num1 = Double.parseDouble(txt11.getText().toString());
    double num2 = Double.parseDouble(txt22.getText().toString());

    double resultado = num1+num2;

    result.setText(String.valueOf(resultado));

}

It doesn't show any code error, but when the button is clicked, this error comes:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()'

What is going wrong?

From your code and stacktrace, it is clear that one of the edittext's is null.

so make sure you are using right id's and inflating right layouts.

Also, from the code, there seems to be a typo.

R.id.txt1 and R.id.text2

Usually people follow coding standards in their own style, but these two id's doesn't match the style.

From what I understood you have 2 edittext and a button in your layout. You need to put this code

double num1 = Double.parseDouble(txt11.getText().toString());    
double num2 = Double.parseDouble(txt22.getText().toString());
double resultado = num1+num2;
result.setText(String.valueOf(resultado));

Inside the setOnClickListener of your button.

Are you sure txt1 and text2 are correct? Maybe one of them is TextView

EditText txt11 = (EditText)findViewById(R.id.txt1); EditText txt22 = (EditText)findViewById(R.id.text2);

It seems that a value is null or invalid . I usually name the view and the variables with the same or very similar name to avoid confusions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM