mangasaske
mangasaske

Reputation: 94

Pass ArrayList objects to another acivity by reference

I have one activity that sends an object arraylist to another activity.

public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener {

    private ArrayList<Value> values;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...

        values = new ArrayList<>();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent i;
        switch(position){
            case 0:
                i = new Intent(MainActivity.this, Main2Activity.class);
                i.putExtra("Values", values);
                startActivity(i);
                break;
            case 1:
                i = new Intent(MainActivity.this, Main3Activity.class);
                i.putExtra("Values",values);
                startActivity(i);
                break;
        }
    }
}

And when I add or remove a value in any other activity the ArrayList doesn't change in my MainActivity. For example:

public class Main2Activity extends AppCompatActivity{

    private ArrayList<Value> values;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        ...

        values = (ArrayList<Value>) getIntent().getSerializableExtra("Values");

        ...

        values.add(value1, value2);
        this.finish();
    }

    ...
}

I would like to know how I should send my ArrayList by reference so I can add, remove or modify it without losing the changes.

Upvotes: 0

Views: 169

Answers (1)

Cory Charlton
Cory Charlton

Reputation: 8938

The extra data you pass in an Intent is serialized and as such cannot be passed by reference.

A simple solution would be using a static field somewhere to share the data between the Activitys

Upvotes: 3

Related Questions