0

I know that having static references in the MainActivity class will cause a memory leak but I have to access an object in MainActivity.

I have a MainActivity object in a RecyclerView ViewHolder class and I get the existing instance of MainActivity by getting the context from a provided view and casting it to MainActivity, could this cause any problems or memory leaks?

Here's what i'm doing:

public class songRecyclerVH extends RecyclerView.ViewHolder implements songRecyclerRowView {

TextView artist;
TextView title;
ImageView albumart;
MainActivity mainActivity;

public songRecyclerVH(final View itemView) {
    super(itemView);

    artist = itemView.findViewById(R.id.artist);
    title = itemView.findViewById(R.id.title);
    albumart = itemView.findViewById(R.id.albumart);
    title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mainActivity = (MainActivity) view.getContext();
            mainActivity.presenter.onSongClicked((Integer.valueOf(title.getTag().toString())));
        }
    });
}
J.D
  • 51
  • 7

3 Answers3

4

The code is ok. Context will leak memory when the view is detached from Activity.

You can simply consider using interface to communicate and avoid memory leak.

Sunny
  • 14,522
  • 15
  • 84
  • 129
  • Thank you! I've been reading and it seems interface will work better. Just out of curiosity, how will it leak memory when the view is detached? – J.D Nov 06 '17 at 07:20
  • @J.D the code is ok. It'll not leak memory. because when activity will get destroy your recycler view will not be visible and user can not click on item. But in general case where you are using Context out of onClick. It will leak memory. So better use interfaces. – Sunny Nov 06 '17 at 07:23
  • read here more https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html Accept the answer if it helps you. :) – Sunny Nov 06 '17 at 07:39
0

be more specific about the object you're trying to access.

but in general, consider using either a Mediator class or an interface for communicating between Activities and other view related classes. or simply just pass the object to the Adapter's Constructor and whenever it changes just call the

notifyDataSetChanged();

there's no need to go through with such a terrible memory leak.

AndroidSmoker74
  • 288
  • 4
  • 19
0

you can use EventBus to avoid memory leak instead having static references .

Amin Rahkan
  • 119
  • 3
  • 11