Roach
Roach

Reputation: 611

How to access a variable declared in the main activity in another activity

i don't know if this is possible or if they is a better programming practice but i'd like to know how to use a varible declared in the main activity in another activity. Source code snippet example is given like so...

public class MainActivity extends ActionBarActivity {
private int a, b;
private EditText first, second;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    first = (EditText) findViewById(R.id.first_entry);
    second = (EditText) findViewById(R.id.second_entry);   }

public void doMath(View view) throws Exception {
    try {
        if (!first.getText().toString().equals("")) {
            a = Integer.parseInt(first.getText().toString());
        }
        else {
            a = 0;
        }
        if (!second.getText().toString().equals("")) {
            b = Integer.parseInt(gpa_credits1.getText().toString());
        }
        else {
            b = 0;
        }

        int sum = a + b;    }catch (Exception e) {}

now, i would like to create a new activity to use the variable "sum" to do some math like...

public class first_year_second_semester extends Activity {


 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newActivity);
    int blah = 5;
    private TextView soln;
    soln = (TextView) findViewById(R.id.the_soln);
    soln = (blah / sum) //i.e sum from the previous activity...please i need this
}

Upvotes: 2

Views: 10523

Answers (2)

Aakash
Aakash

Reputation: 5261

You can pass the value from one to other activity using intent or using shared preferences.

Intent intent=new Intent(MainActivity.this,year_second_semester.class);
intent.putExtras("sum",sum);
startActivity(intent);

Then in next activity you can get this value.

Or using shared preferences: Inside class: SharedPreferences shared;

Inside onCreate: shared=getSharedPreferences("app",Context.MODE_PRIVATE);

After computing the sum I.e. after doing sum=a+b;

Editor edit=shared.edit();
edit.putString("sum",sum);
edit.commit();

And in the next activity: Inside the class: SharedPreferences shared;

Inside oncreate: shared=getSharedPreferences("app",Context.MODE_PRIVATE);

Wherver you want: String yourvalue=shared.getString("sum","default value");

Here your value will be the sum from the main activity.

Upvotes: 3

TameHog
TameHog

Reputation: 950

Create a public static variable in your main activity (where the do math method is) like so:

public static int SUM;

Then in the do math function set that value to the one calculated.

int sum = a+b;
SUM = sum;

Then you can access it via:

MainActivity.SUM

Upvotes: 3

Related Questions