Home >Java >javaTutorial >How to Send an Integer Array Between Activities in Android?
Problem:
An array of integers is being sent from Activity A to Activity B using Intent.putExtra. However, in Activity B, the array is received as '0'.
Background:
Intent.putExtra() is commonly used to send small data types like strings, integers, and doubles between activities. However, it is not directly applicable to arrays.
Incorrect Approach:
<code class="java">i.putExtra("numbers", array);</code>
Issue:
The above code attempts to put an integer array into the intent as an integer. This is incorrect because an array cannot fit into a single integer.
Correct Approach:
To send an array using Intent.putExtra, it must be converted to a form that can be stored as a single value. This can be achieved by using the getIntArray() and putExtraIntArray() methods.
<code class="java">// Sending array from Activity A i.putExtra("numbers", array); // Receiving array in Activity B int[] arrayB = extras.getIntArray("numbers");</code>
Additional Notes:
Ensure that both activities have identical array declarations to avoid runtime errors. It is also good practice to check if the intent contains the expected extra before accessing it.
The above is the detailed content of How to Send an Integer Array Between Activities in Android?. For more information, please follow other related articles on the PHP Chinese website!