Saturday, May 10, 2014

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

1) First Activity

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 {
public static final String TAG="tag";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        final ArrayList<String> mArray = new ArrayList<String>();
        mArray.add("orange");
        mArray.add("apple");
         
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
             
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Second.class);
                intent.putExtra(TAG, mArray);
                startActivity(intent);
                 
            }
        });
         
         
    }
}
2) Second Activity
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
 
public class SecondActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
         
        Bundle b = getIntent().getExtras();
         
        if(b!=null){
            ArrayList<String> mArray = (ArrayList<String>)b.getStringArrayList(MainActivity.TAG);
            System.out.println(mArray);
        }   
      
    }
}

1 comment:

  1. Hello, an amazing Information dude. Thanks for sharing this nice information with us. Covid-19 Cleaning Services Folsom

    ReplyDelete