DawnDusk DawnDusk - 1 year ago 202
Android Question

Android - A variable might not have been initialized

Trying to create a BMI Calculator I already declared a variable for weight and height, but still I'm getting an error of "variable "weight" might not have been initialized.

public class MainActivity extends AppCompatActivity {

private EditText eheight, eweight;
private Button computeb;
private TextView output, category;

protected void onCreate(Bundle savedInstanceState) {

eheight = (EditText) findViewById(R.id.eheight);
eweight = (EditText) findViewById(R.id.eweight);
output = (TextView) findViewById(R.id.output);
category = (TextView) findViewById(R.id.category);
computeb = (Button) findViewById(R.id.computeb);

computeb.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {

float weight, height, BMI;

if (checkInputLength())
weight = Float.parseFloat(weight.getText().toString());
height = Float.parseFloat(height.getText().toString());
computeBMI(weight, height);

BMI = weight / (height * height);

Answer Source


weight = Float.parseFloat(weight.getText().toString());
height = Float.parseFloat(height.getText().toString());


weight = Float.parseFloat(eweight.getText().toString());
height = Float.parseFloat(eheight.getText().toString());

weight and height are just float variables.If you want to parse data from edittext then you have to get the data from the edittexts and store them in the corresponding variables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download