Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending arrays with Intent.putExtra

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.

like image 855
Kitinz Avatar asked Oct 03 '10 01:10

Kitinz


People also ask

How do you pass an array using intent?

putExtra("numbers", array); startActivity(i); In the activity B I get the info: Bundle extras = getIntent(). getExtras(); int arrayB = extras.

What is the putExtra () method used with intent for?

Using putExtra() We can start adding data into the Intent object, we use the method defined in the Intent class putExtra() or putExtras() to store certain data as a key value pair or Bundle data object. These key-value pairs are known as Extras in the sense we are talking about Intents.

How do you pass an activity in intent?

The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity: Intent intent = new Intent(getBaseContext(), SignoutActivity. class); intent. putExtra("EXTRA_SESSION_ID", sessionId); startActivity(intent);

What is difference between intent and bundle?

Bundles are used with intent and values are sent and retrieved in the same fashion, as it is done in the case of Intent. It depends on the user what type of values the user wants to pass, but bundles can hold all types of values (int, String, boolean, char) and pass them to the new activity.


2 Answers

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"); 
like image 156
Mark B Avatar answered Oct 16 '22 13:10

Mark B


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"); 
like image 27
Khalid Habib Avatar answered Oct 16 '22 12:10

Khalid Habib