69

I have an array of integers in the activity A:

int array[] = {1,2,3};

And I want to send that variable to the activity B, so I create a new intent and use the putExtra method:

Intent i = new Intent(A.this, B.class);
i.putExtra("numbers", array);
startActivity(i);

In the activity B I get the info:

Bundle extras = getIntent().getExtras();
int arrayB = extras.getInt("numbers");

But this is not really sending the array, I just get the value '0' on the arrayB. I've been looking for some examples but I didn't found anything so.

user3678528
  • 1,741
  • 2
  • 18
  • 24
Kitinz
  • 1,522
  • 3
  • 17
  • 28

3 Answers3

91

You are setting the extra with an array. You are then trying to get a single int.

Your code should be:

int[] arrayB = extras.getIntArray("numbers");
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • 6
    Ouch! I was focused on the putExtra and getExtras syntax that i didnt realize the misstake was so obvious :D Thank you! – Kitinz Oct 03 '10 at 11:40
  • @Kitinz +1 for to be very nice on community ... I liked that :) – Adnan Jan 20 '16 at 13:27
9

This code sends array of integer values

Initialize array List

List<Integer> test = new ArrayList<Integer>();

Add values to array List

test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);

Send the array list values to target activity

intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);

here you get values on targetActivty

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
Khalid Habib
  • 1,100
  • 1
  • 16
  • 25
-2
final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}
highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91