Java – How do I access an object (e.g. ArrayList) from another class?

How do I access an object (e.g. ArrayList) from another class?… here is a solution to the problem.

How do I access an object (e.g. ArrayList) from another class?

I’m looking for a way that allows me to access objects from another class; Both classes are in the same Android activity – OpenStreeMapActivity .java. I have:

ItemizedOverlay.java – Contains the objects I want to access and modify:

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

BalloonOverlayView.java – This is where I want to access the object mOverlays:

    protected void setupView(final Context context, final ViewGroup parent) {

LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.balloon_overlay, parent);
    title = (TextView) v.findViewById(R.id.balloon_item_title);
    snippet = (TextView) v.findViewById(R.id.balloon_item_snippet);

 Get ballon_close button and register its listener:
    ImageView close = (ImageView) v.findViewById(R.id.balloon_close);
    close.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            parent.setVisibility(GONE); 

Intent intent = new Intent( );
            intent.setClassName( "org.example.openstreetmap", "org.example.openstreetmap.UpdateEntityActivity" );
            v.getContext().startActivity(intent);

HERE I return from UpdateOverlayActivity.java and is where I want to modify *mOverlays*.
        }
    });

} 

EDIT: I found it incorrect that I returned //HERE.

Solution

In ItemizedOverlay, create a method that provides the object.

public List<OverlayItem> getOverlays() {
  return this.mOverlays;
}

It’s better if you use List, and if you want to change the implementation in the future, it won’t affect your code elsewhere.

Related Problems and Solutions