2

I am working on an Android class that contains an ArrayList of generic objects. I am looking to fire an event in this class whenever an element of said ArrayList is modified.

In an ideal world, the ArrayList itself should be a private member, and the class would contain the public methods to add/update/delete an element and everything would be all fine and dandy.

Unfortunately, the ArrayList is exposed as a public member, so it and its elements are being modified all over the place (application). Without rewriting a boat load of code and/or going on a wild goose chase in the code, I am hoping I can find way to trigger an event when ArrayList is modified in the class containing the list. Any ideas?

1 Answer 1

5

You can subclass ArrayList and trigger an action (call a callback for example) after some of it's methods were invoked.

Then replace the original ArrayList in your Android class with your implementation.

P.S. Example:

public class MyArrayList<E> extends ArrayList<E> {

@Override
public boolean add(E object) {
    // Do some action here
    return super.add(object);
};

@Override
public void add(int index, E object) {
    super.add(index, object);
    // Do some action here
};

@Override
public E remove(int index) {
    // Do some action here
    return super.remove(index);
}
// etc...

}

Since it subclasses ArrayList you won't get any errors in your code, and everything that worked before, will work without any changes. With a little creativity the class can be made more elegant and efficient, but the general idea is there.

Edit: Yep. Sorry, was a little hasty with those returns. Fixed, and thanks Petar

Sign up to request clarification or add additional context in comments.

1 Comment

After return super.add(object); // Do some action here will not be executed. You must capture the value of super.add(object); do your stuff and then return the captured value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.