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

By | October 28, 2012

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.

package com.coderzheaven.passarraylist;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final ArrayList arr = new ArrayList();
        arr.add("Hello");
        arr.add("CoderzHeaven");
        
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, Second.class);
				intent.putExtra("array_list", arr);
				startActivity(intent);
				
			}
		});
        
        
    }
}

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

package com.coderzheaven.passarraylist;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;

public class Second extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
        
        Bundle b = getIntent().getExtras();
        
        if(b!=null){
        	ArrayList arr = (ArrayList)b.getStringArrayList("array_list");
        	System.out.println(arr);
        }    
     
    }
}

This is the AndroidManifest file.

Please check the LogCat for the Output.

Download complete tutorial PDF from below.

Pass ArrayList Tutorial PDF

Leave a Reply

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