[android] How to pass ArrayList of Objects from one to another activity using Intent in android?

I have the following in code in my onClick() method as

 List<Question> mQuestionsList = QuestionBank.getQuestions();

Now I have the intent after this line, as follows :

  Intent resultIntent = new Intent(this, ResultActivity.class);
  resultIntent.putParcelableArrayListExtra("QuestionsExtra", (ArrayList<? extends Parcelable>) mQuestionsList);
  startActivity(resultIntent);

I don't know how to pass this question lists in the intent from one activity to another activity My Question class

public class Question {
    private int[] operands;
    private int[] choices;
    private int userAnswerIndex;

    public Question(int[] operands, int[] choices) {
        this.operands = operands;
        this.choices = choices;
        this.userAnswerIndex = -1;
    }

    public int[] getChoices() {
        return choices;
    }

    public void setChoices(int[] choices) {
        this.choices = choices;
    }

    public int[] getOperands() {
        return operands;
    }

    public void setOperands(int[] operands) {
        this.operands = operands;
    }

    public int getUserAnswerIndex() {
        return userAnswerIndex;
    }

    public void setUserAnswerIndex(int userAnswerIndex) {
        this.userAnswerIndex = userAnswerIndex;
    }

    public int getAnswer() {
        int answer = 0;
        for (int operand : operands) {
            answer += operand;
        }
        return answer;
    }

    public boolean isCorrect() {
        return getAnswer() == choices[this.userAnswerIndex];
    }

    public boolean hasAnswered() {
        return userAnswerIndex != -1;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        // Question
        builder.append("Question: ");
        for(int operand : operands) {
            builder.append(String.format("%d ", operand));
        }
        builder.append(System.getProperty("line.separator"));

        // Choices
        int answer = getAnswer();
        for (int choice : choices) {
            if (choice == answer) {
                builder.append(String.format("%d (A) ", choice));
            } else {
                builder.append(String.format("%d ", choice));
            }
        }
        return builder.toString();
       }

      }

This question is related to android android-intent parcelable

The answer is


Simple as that !! worked for me

From activity

        Intent intent = new Intent(Viewhirings.this, Informaall.class);
        intent.putStringArrayListExtra("list",nselectedfromadapter);

        startActivity(intent);

TO activity

Bundle bundle = getIntent().getExtras();
    nselectedfromadapter= bundle.getStringArrayList("list");

You can use parcelable for object passing which is more efficient than Serializable .

Kindly refer the link which i am share contains complete parcelable sample. Click download ParcelableSample.zip


Your arrayList:

ArrayList<String> yourArray = new ArrayList<>();

Write this code from where you want intent:

Intent newIntent = new Intent(this, NextActivity.class);
newIntent.putExtra("name",yourArray);
startActivity(newIntent);

In Next Activity:

ArrayList<String> myArray = new ArrayList<>();

Write this code in onCreate:

myArray =(ArrayList<String>)getIntent().getSerializableExtra("name");

You must need to also implement Parcelable interface and must add writeToParcel method to your Questions class with Parcel argument in Constructor in addition to Serializable. otherwise app will crash.


Implements Parcelable and send arraylist as putParcelableArrayListExtra and get it from next activity getParcelableArrayListExtra

example:

Implement parcelable on your custom class -(Alt +enter) Implement its methods

public class Model implements Parcelable {

private String Id;

public Model() {

}

protected Model(Parcel in) {
    Id= in.readString();       
}

public static final Creator<Model> CREATOR = new Creator<Model>() {
    @Override
    public ModelcreateFromParcel(Parcel in) {
        return new Model(in);
    }

    @Override
    public Model[] newArray(int size) {
        return new Model[size];
    }
};

public String getId() {
    return Id;
}

public void setId(String Id) {
    this.Id = Id;
}


@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(Id);
}
}

Pass class object from activity 1

 Intent intent = new Intent(Activity1.this, Activity2.class);
            intent.putParcelableArrayListExtra("model", modelArrayList);
            startActivity(intent);

Get extra from Activity2

if (getIntent().hasExtra("model")) {
        Intent intent = getIntent();
        cartArrayList = intent.getParcelableArrayListExtra("model");

    } 

You can pass the arraylist from one activity to another by using bundle with intent. Use the code below This is the shortest and most suitable way to pass arraylist

bundle.putStringArrayList("keyword",arraylist);


Pass your object via Parcelable. And here is a good tutorial to get you started.
First Question should implements Parcelable like this and add the those lines:

public class Question implements Parcelable{
    public Question(Parcel in) {
        // put your data using = in.readString();
  this.operands = in.readString();;
    this.choices = in.readString();;
    this.userAnswerIndex = in.readString();;

    }

    public Question() {
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(operands);
        dest.writeString(choices);
        dest.writeString(userAnswerIndex);
    }

    public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {

        @Override
        public Question[] newArray(int size) {
            return new Question[size];
        }

        @Override
        public Question createFromParcel(Parcel source) {
            return new Question(source);
        }
    };

}

Then pass your data like this:

Question question = new Question();
// put your data
  Intent resultIntent = new Intent(this, ResultActivity.class);
  resultIntent.putExtra("QuestionsExtra", question);
  startActivity(resultIntent);

And get your data like this:

Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
    question = extras.getParcelable("QuestionsExtra");
}

This will do!


Your intent creation seems correct if your Question implements Parcelable.

In the next activity you can retrieve your list of questions like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}

To set the data in kotlin

val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)

To get the data

 val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?

Now access the arraylist


Steps:

  1. Implements your object class to serializable

    public class Question implements Serializable`
    
  2. Put this in your Source Activity

    ArrayList<Question> mQuestionList = new ArrayList<Question>;
    mQuestionsList = QuestionBank.getQuestions();  
    mQuestionList.add(new Question(ops1, choices1));
    
    Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
    intent.putExtra("QuestionListExtra", mQuestionList);
    
  3. Put this in your Target Activity

     ArrayList<Question> questions = new ArrayList<Question>();
     questions = (ArrayList<Questions>) getIntent().getSerializableExtra("QuestionListExtra");
    

Between Activity: Worked for me

ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);

In the Transfer.class

Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");

Hope this help's someone.

Using Parcelable to pass data between Activity

This usually works when you have created DataModel

e.g. Suppose we have a json of type

{
    "bird": [{
        "id": 1,
        "name": "Chicken"
    }, {
        "id": 2,
        "name": "Eagle"
    }]
}

Here bird is a List and it contains two elements so

we will create the models using jsonschema2pojo

Now we have the model class Name BirdModel and Bird BirdModel consist of List of Bird and Bird contains name and id

Go to the bird class and add interface "implements Parcelable"

add implemets method in android studio by Alt+Enter

Note: A dialog box will appear saying Add implements method press Enter

The add Parcelable implementation by pressing the Alt + Enter

Note: A dialog box will appear saying Add Parcelable implementation and Enter again

Now to pass it to the intent.

List<Bird> birds = birdModel.getBird();
Intent intent = new Intent(Current.this, Transfer.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Birds", birds);
intent.putExtras(bundle);
startActivity(intent);

And on Transfer Activity onCreate

List<Bird> challenge = this.getIntent().getExtras().getParcelableArrayList("Birds");

Thanks

If there is any problem please let me know.


I had the exact same question and while still hassling with the Parcelable, I found out that the static variables are not such a bad idea for the task.

You can simply create a

public static ArrayList<Parliament> myObjects = .. 

and use it from elsewhere via MyRefActivity.myObjects

I was not sure about what public static variables imply in the context of an application with activities. If you also have doubts about either this or on performance aspects of this approach, refer to:

Cheers.


I do one of two things in this scenario

  1. Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)

  2. Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.

Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.


If your class Question contains only primitives, Serializeble or String fields you can implement him Serializable. ArrayList is implement Serializable, that's why you can put it like Bundle.putSerializable(key, value) and send it to another Activity. IMHO, Parcelable - it's very long way.


The easiest way to pass ArrayList using intent

  1. Add this line in dependencies block build.gradle.

    implementation 'com.google.code.gson:gson:2.2.4'
    
  2. pass arraylist

    ArrayList<String> listPrivate = new ArrayList<>();
    
    
    Intent intent = new Intent(MainActivity.this, ListActivity.class);
    intent.putExtra("private_list", new Gson().toJson(listPrivate));
    startActivity(intent);
    
  3. retrieve list in another activity

    ArrayList<String> listPrivate = new ArrayList<>();
    
    Type type = new TypeToken<List<String>>() {
    }.getType();
    listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
    

You can use object also instead of String in type

Works for me..


Your bean or pojo class should implements parcelable interface.

For example:

public class BeanClass implements Parcelable{
    String name;
    int age;
    String sex;

    public BeanClass(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    } 
     public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
        @Override
        public BeanClass createFromParcel(Parcel in) {
            return new BeanClass(in);
        }

        @Override
        public BeanClass[] newArray(int size) {
            return new BeanClass[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeString(sex);
    }
}

Consider a scenario that you want to send the arraylist of beanclass type from Activity1 to Activity2.
Use the following code

Activity1:

ArrayList<BeanClass> list=new ArrayList<BeanClass>();

private ArrayList<BeanClass> getList() {
    for(int i=0;i<5;i++) {

        list.add(new BeanClass("xyz", 25, "M"));
    }
    return list;
}
private void gotoNextActivity() {
    Intent intent=new Intent(this,Activity2.class);
    /* Bundle args = new Bundle();
    args.putSerializable("ARRAYLIST",(Serializable)list);
    intent.putExtra("BUNDLE",args);*/

    Bundle bundle = new Bundle();
    bundle.putParcelableArrayList("StudentDetails", list);
    intent.putExtras(bundle);
    startActivity(intent);
}

Activity2:

ArrayList<BeanClass> listFromActivity1=new ArrayList<>();

listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");

if (listFromActivity1 != null) {

    Log.d("listis",""+listFromActivity1.toString());
}

I think this basic to understand the concept.


I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.

ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
    Question question = questionList.get(i);
    intent.putExtra("question" + i, question);
}
startActivity(intent);

And now in Second Activity

ArrayList<Question> questionList = new ArrayList<>();

Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
    Question model = (Question) intent.getSerializableExtra("question" + i);
    questionList.add(model);
    i++;
}

Note: implements Serializable in your Question class.


You can Pass Arraylist/Pojo using bundle like this ,

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
                        args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
                        intent.putExtra("BUNDLE",args);
 startActivity(intent); 

Get those values in SecondActivity like this

  Intent intent = getIntent();
        Bundle args = intent.getBundleExtra("BUNDLE");
  String filter = bundle.getString("imageSliders");

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-intent

Kotlin Android start new Activity Open Facebook Page in Facebook App (if installed) on Android Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23 Not an enclosing class error Android Studio Parcelable encountered IOException writing serializable object getactivity() Sending intent to BroadcastReceiver from adb How to pass ArrayList<CustomeObject> from one activity to another? Android Intent Cannot resolve constructor Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT Android - java.lang.SecurityException: Permission Denial: starting Intent

Examples related to parcelable

How to pass ArrayList of Objects from one to another activity using Intent in android? How can I make my custom objects Parcelable? How to read/write a boolean when implementing the Parcelable interface? How to send objects through bundle Android: Difference between Parcelable and Serializable? How can I pass a Bitmap object from one activity to another