android tab pass intent extras to new tabs activity

Dean-O picture Dean-O · Dec 24, 2010 · Viewed 8.6k times · Source

I have read through the similar questions but do not see one like this. I have a simple calculator application there are two tabs. Each has their own activity class. I initially wrote this with a button on the first screen which onClick would take the inputs and pass them to the results screen which would do some calculation and then display the results. Now I want to do it with a TabHost. I have the two screens all set, but no idea how to take the inputs and pass them to the results activity to do the calculations and display the resulting values.

Thanks in advance Dean-O

Answer

michaelg picture michaelg · Dec 24, 2010

The most natural way to do this would be to provide your own subclass of android.app.Application and use it to store the shared data. Then the first tab would set the values in the data structure, and the second tab would read them and use them to perform whatever calculation you wanted to do. See here: How to declare global variables in Android?

Assuming you don't want to take this approach and really want to use Intent extras to pass the data between Activities within a TabHost, you could do something like the following hack where you use the TabHosts Intent (accessed via getParent().getIntent()) to pass data back and forth.

 public class Tab1 extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.tab_one);
  Button button = (Button) findViewById(R.id.btn);
  button.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v) {
    EditText x = (EditText) findViewById(R.id.x);
    EditText y = (EditText) findViewById(R.id.y);
    int a = Integer.parseInt(x.getText().toString());
    int b = Integer.parseInt(y.getText().toString());
    Intent i = getParent().getIntent();
    i.putExtra("a", a);
    i.putExtra("b", b);
    i.putExtra("tab", 1);
    TabActivity ta = (TabActivity) Tab1.this.getParent();
    ta.getTabHost().setCurrentTab(1);
   }
  });
 }
}


public class Tab2 extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TextView result = new TextView(this);
  Intent i = getParent().getIntent();
  int a = i.getIntExtra("a", 0);
  int b = i.getIntExtra("b", 0);
  int sum = a + b;
  result.setText(Integer.toString(sum));
        setContentView(result);
 }
}