How to pass integer from one Activity to another?

I would like to pass a new value for an integer from one Activity to another. i.e.:

Activity B contains an

integer[] pics = { R.drawable.1, R.drawable.2, R.drawable.3}

I would like activity A to pass a new value to activity B:

integer[] pics = { R.drawable.a, R.drawable.b, R.drawable.c}

So that somehow through

private void startSwitcher() {
    Intent myIntent = new Intent(A.this, B.class);
    startActivity(myIntent);
}

I can set this integer value.

I know this can be done somehow with a bundle, but I am not sure how I could get these values passed from Activity A to Activity B.


Solution 1:

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

Solution 2:

Their are two methods you can use to pass an integer. One is as shown below.

A.class

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

B.class

Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);

The other method converts the integer to a string and uses the following code.

A.class

Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);

The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.

B.class

   Bundle extras = getIntent().getExtras();
   String stringVariableName = extras.getString("StringVariableName");
   int intVariableName = Integer.parseInt(stringVariableName);

Solution 3:

In Activity A

private void startSwitcher() {
    int yourInt = 200;
    Intent myIntent = new Intent(A.this, B.class);
    intent.putExtra("yourIntName", yourInt);
    startActivity(myIntent);
}

in Activity B

int score = getIntent().getIntExtra("yourIntName", 0);