46

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.

Benny
  • 2,233
  • 1
  • 22
  • 27
benbeel
  • 1,532
  • 4
  • 24
  • 38

4 Answers4

140

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);
outis
  • 75,655
  • 22
  • 151
  • 221
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
8

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);
Benny
  • 2,233
  • 1
  • 22
  • 27
Daniel Nyamasyo
  • 2,152
  • 1
  • 24
  • 23
4

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);
Benny
  • 2,233
  • 1
  • 22
  • 27
Lone Coder
  • 85
  • 2
  • 9
0

In Sender Activity Side:

Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);

In Receiver Activity Side:

int receiveValue = getIntent().getIntExtra("value", 0);
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51