Android pass array to another activity

In your Android application, it is common to pass data from an Activity to another Activity. The data can be of the following types: boolean, byte, char, int, long, float, double, string, etc. You can also pass an array or an object that is a collection of data. In this Android tip, I am going to show you how to pass an array.



You can pass boolean, byte, char, int, long, float, double, and even string array using the putExtra() method of the Intent object that is sent to another activity. In the destination Activity, you are able to get the Bundle object that contains the array using getExtra() method of the received Intent object. Then you can get the array from the Bundle object using a method of the Bundle object. There are different methods to help you get the arrays of different types. If you passed an integer array, you use getIntArray(). If you passed a string array, you use getStringArray().

To be more precise, you create a new project in Android Studio. In the project, you create two activities: MainActivity and SecondActivity. An integer array will be passed from the first activity to the second activity. So, in onCreate() method of the MainActivity, you write code as shown below.

int[] myArr={12,34,54,54};
     // Construct an Intent object that targets the SecondActivity
     Intent intent = new Intent(this,SecondActivity.class);
     intent.putExtra("myArr",myArr);
     // Start the SecondActivity
     startActivity(intent);

To receive the passed array, in onCreate() method of the SecondActivity, you write the following code:

// Get Bundle object that contain the array
     Bundle extras = getIntent().getExtras();
     // Extract the array from the Bundle object
     int[] myArr= extras.getIntArray("myArr");
     // Output the array
     for(int item:myArr){
        Log.i("SecondActivity", String.valueOf(item));
     }

Android-pass-array-to-another-activity

Posted by: Dara | post date: 02-20-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.