Home > Enterprise >  Adding to an ArrayList on click from another activity
Adding to an ArrayList on click from another activity

Time:06-02

I'm trying to keep adding to an array list every time I click a button from another activity.

arrayList = new ArrayList<>();
                    arrayList.add(name);
                    arrayList.add(price);
                    arrayList.add(quantity);

CodePudding user response:

First and foremost, you should have provided us with additional information. Regarding your issue now, I suppose that you could have created a serializable object instead of a list, like this:

public class CustomObject implements Serializable{
private String name;
private double price;
private int quantity;
// constructor etc here
}

then you could have passed the object between activities like this:

Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
i.putExtra("object", customObject);
startActivity(i);

and then in your new activity:

Intent i = getIntent();
CustomObject obj = i.getSerializableExtra("object");

Passing a list from one activity to another works similarly, but I see that you're using your list incorrectly, without declaring what object types it stores. I'm guessing the name will be a String and the quantity will be a number...

In any case, here's how to pass a list across activities:

Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
i.putExtra("list", arrayList);
startActivity(i);

and then in your new activity:

Intent i = getIntent();
arrayList = i.getSerializableExtra("list");

CodePudding user response:

Use shared prefs and clear them when you are done

  • Related