Home > Java > javaTutorial > How to Send an Integer Array Between Activities in Android?

How to Send an Integer Array Between Activities in Android?

Barbara Streisand
Release: 2024-10-25 10:57:02
Original
630 people have browsed it

How to Send an Integer Array Between Activities in Android?

Incorrect Array Transfer with Intent.putExtra

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template