How to pass an arraylist value from one activity to another in android?

By | January 9, 2018

This simple example shows how to pass an ArrayList from one activity to another in Android.

This is the first activity on which we are sending the arrayList.

MainActivity

package com.coderzheaven.passarraylist;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passArrayList();
            }
        });
    }

    private void passArrayList() {
        final ArrayList<String> arr = new ArrayList<>();
        arr.add("Hello");
        arr.add("CoderzHeaven");

        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        intent.putExtra("array_list", arr);
        startActivity(intent);
    }

}

Now this is the Second activity in which we are receiving the passed arrayList.

SecondActivity

package com.coderzheaven.passarraylist;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.ArrayList;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second_activity);
        Bundle b = getIntent().getExtras();

        if (null != b) {
            ArrayList<String> arr = b.getStringArrayList("array_list");
            Log.i("List", "Passed Array List :: " + arr);
        }

    }
}

Please check the Logcat for the Output.

Source code

You can download the Android Studio source code from here.

Leave a Reply

Your email address will not be published. Required fields are marked *