2016-07-06 76 views
2

我想建立一個BMI計算器應用程序,但是,似乎有使用意圖和getIntExtra()方法的問題,因爲我總是得到默認值,而不是我從另一項活動中獲得的價值。 下面是我的第一個活動代碼Android的BMI計算器應用程序錯誤的意圖

calculate.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(getApplicationContext(), SecondActivity.class); 

      int weight = Integer.parseInt(weightText.getText().toString()); 
      int height = Integer.parseInt(heightText.getText().toString()); 

      intent.putExtra(USER_WEIGHT_EXTRA, weight); 
      intent.putExtra(USER_HEIGHT_EXTRA, height); 
      startActivity(intent); 
     } 
    }); 

次活動 雙height2 = (double)height/100的原因是從釐米轉換爲m。

result = (TextView)findViewById(R.id.result); 
    todo = (TextView) findViewById(R.id.todo); 

    Intent intent = getIntent(); 

    int weight = intent.getIntExtra("USER_WEIGHT_EXTRA", extraInt); 
    int height = intent.getIntExtra("USER_HEIGHT_EXTRA", extraInt); 

    double height2 = (double)height/100; 
    double BMI = (weight*1.0)/(height2*height2); 


    if (BMI < 20.0) { 
     result.setText("You are: UNDERWEIGHT"); 
     todo.setText("You Should EAT MORE"); 
    } else if (BMI > 20.0 && BMI < 25.0) { 
     result.setText("You are: NORMAL WEIGHT"); 
     todo.setText("You Should keep STAYING HEALTHY"); 
    } else if (BMI > 25) { 
     result.setText("You are: OVERWEIGHT"); 
     todo.setText("You Should EXERCISE MORE"); 
    } 
} 

我真的被困在這個問題上。非常感謝你!

+0

確實'USER_WEIGHT_EXTRA = 「USER_WEIGHT_EXTRA」'?高度相同。您在第一個活動中使用變量,在第二個活動中使用字符串,可能是問題 – ElefantPhace

+0

第一個活動中的USER_WEIGHT_EXTRA是一個字符串變量,它包含字符串「USER_WEIGHT_EXTRA」 – hwhong

+0

因此我的問題的答案是肯定的。 – ElefantPhace

回答

0

在第一活動

Intent in = new Intent(this, OtherActivity.class); 
      in.putExtra("USER_WEIGHT_EXTRA", weightText.getText().toString()); 
      in.putExtra("USER_HEIGHT_EXTRA", heightText.getText().toString()); 
      startActivity(in);` 

爲otherActivity

Bundle bundle = getIntent().getExtras(); 

     int weight = Integer.parseInt(bundle.getString("USER_WEIGHT_EXTRA")); 
     int height = Integer.parseInt(bundle.getString("USER_HEIGHT_EXTRA")); 
+2

謝謝!有效! – hwhong

+0

很高興幫助,請接受並關閉線程 –