我試圖從一個活動傳遞兩個數字輸入到其他的UI,但是當我點擊按鈕來改變意圖崩潰。如何將意圖數據設置爲當前活動editText?
我在logcat中得到了以下內容:http://pastebin.com/zkWPcSNZ,這表明我在解析數據到CalcResult中的editTexts時出現了問題。
我的問題是,什麼是錯的,我試圖將數據傳遞到CalcResult editText.Is有acheiving本的替代方法的方式嗎?
我的兩個類看起來像這樣以供參考:
public class MainActivity extends Activity implements OnClickListener {
//variables for xml objects
EditText offsetLength,offsetDepth,ductDepth;
Button calculate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting the variables to the xml id's and setting the click listener on the calc button
offsetLength = (EditText)findViewById(R.id.offLength);
offsetDepth = (EditText)findViewById(R.id.offDepth);
ductDepth = (EditText)findViewById(R.id.ductDepth);
calculate = (Button)findViewById(R.id.calc);
calculate.setOnClickListener(this);//don't cast the listener to OnClickListener
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String getoffsetlength = offsetLength.getText().toString();
String getoffsetdepth = offsetDepth.getText().toString();
String getductdepth = ductDepth.getText().toString();
double tri1,tri2;
double marking1,marking2;
double off1 = Double.parseDouble(getoffsetlength);
double off2 = Double.parseDouble(getoffsetdepth);
double off3 = Double.parseDouble(getductdepth)
;
marking1 = Math.pow(off1,2) + Math.pow(off2,2);
tri1 = (float)off2/(float)off1;
tri2 = (float)off3/Math.atan((float)tri1);
marking2 = (float)off3/Math.atan(tri2);
Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
myIntent.putExtra("numbers", marking1);
myIntent.putExtra("numbers", marking2);
startActivity(myIntent);
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("Must enter a numeric value!");
}
}
}
這是我在傳遞數據的活動:
public class CalcResult extends MainActivity
{
EditText result1,result2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
result1 = (EditText)findViewById(R.id.mark1);
result2 = (EditText)findViewById(R.id.mark2);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
double mark1 = bundle.getDouble("number1");
double mark2 = bundle.getDouble("number2");
int a = Integer.valueOf(result1.getText().toString());
int b = Integer.valueOf(result2.getText().toString());
result1.setText(a + " ");
result2.setText(b + " ");
}
}
這是由OP產生的錯誤,但不是應用程序崩潰的原因。 'getDouble(String鍵)'_「返回與給定鍵關聯的值,或0.0,如果沒有所需類型的映射存在給定鍵」如果你看看他在其中發送額外的變量的代碼_ –
中,他使用的關鍵是相同的'myIntent.putExtra(「數字」,marking1);',所以關鍵是「數字」,而他正試圖中檢索鍵「數字1」「和數字2」的雙重額外的,所以它將返回0。因此,即使假設他已將文本設置爲EditText,它也不會顯示任何內容 – Houcine
它將返回0,但這不會引發異常。你只需要'mark1 = 0;'和'mark2 = 0;' –