我是新來的Android
我已經學會了如何通過putextra傳遞activites之間的數據,在我的應用程序getextra
,當我從活性1傳遞數據和活性2到main_activity並添加數據和把它傳遞給第三活性(輸出)
代替此外,只有要麼活性1或活性2的值傳遞給輸出正被傳遞(值被一個我在運行我的應用程序時最後輸入的)
這裏是我的應用程序的代碼
Mainactivity如何活動之間傳遞數據和對數據進行算術運算
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent j = getIntent();
a= j.getDoubleExtra("double1",0.0);
Intent k = getIntent();
b = k.getDoubleExtra("double2",0.0);
result = a+b;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void on_click_activity1button(View view) {
Intent intent1 = new Intent(this,activity1.class);
startActivity(intent1);
}
public void on_click_activity2button(View view) {
Intent intent2 = new Intent(this,activity2.class);
startActivity(intent2);
}
public void on_click_outputbutton(View view) {
Intent intent3 = new Intent(this,output.class);
intent3.putExtra("result", result);
startActivity(intent3);
}
}
活性1
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
}
public void on_click_activity1done(View view) {
EditText text1 = (EditText) findViewById(R.id.activity1edittext);
a=Double.parseDouble(text1.getText().toString());
Intent fromactivity1 = new Intent(this,MainActivity.class);
fromactivity1.putExtra("double1", a);
startActivity(fromactivity1);
}
}
Activity2.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
}
public void on_click_activity2done(View view) {
EditText text2 = (EditText) findViewById(R.id.activity2edittext);
b=Double.parseDouble(text2.getText().toString());
Intent fromactivity2 = new Intent(this,MainActivity.class);
fromactivity2.putExtra("double2", b);
startActivity(fromactivity2);
}
}
output.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.output);
Intent frommaindone = getIntent();
Double total = frommaindone.getDoubleExtra("result",0.0);
TextView show = (TextView) findViewById(R.id.resulttextview);
show.setText("addition is" + total);
}
}
請幫助我,並告訴我,我做錯了什麼
你這樣做的方式是不正確的,你正在創建多個主要活動,沒有人的數字將永遠是錯誤的。看看startActivityForResult –
我也試過startActivityForResult,但同樣的問題正在發生 – Navdeep
當我運行我的應用程序,並按下按鈕1以獲取textfrom(雙)activity1之後,當我按下按鈕2以獲得textfrom(雙)activity2,我認爲來自activity1的變量值被銷燬。我想知道如何保留它,以便我可以添加兩個值a和b。 – Navdeep