1

I have gone across many demos on different CustomAdapter but neither demo shows how we can actually get which activity we are using adapter for, inside the adapter. Right now I am using this approach for adapter

private Activity activity;

public CustomAdapter(Activity a, ArrayList d, Resources resLocal) {
    activity = a;
    ....
}

At Activity a I can actually get context but failed to get that on which activity I can use its function. While activity is still opened so there must be something to communicate to its functions. Anyway using following technique by me is totally reckless

try {
    ((HomeActivity) activity).onItemClick(mPosition); // function in other activity
} 
catch (Exception e) {
    ((PlayActivity) activity).onItemClick(mPosition); // function in other activity
}

I am using same CustomAdapter class for more than one activity so using try-catch to automatically find which method will not raise exception as I still do not know about the parent activity.

If anyway we can get to know about it that will be great!

Thanks for reading, Cheers!

  • have you tried instanceof? – Elltz Jun 28 '15 at 23:02
  • I have not tried anything like this but if it can excludes the need of that `try-catch` I will be happy to hear from you. Thanks –  Jun 28 '15 at 23:04
  • 1
    exactly, it will, check [this](http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for), [this](http://stackoverflow.com/questions/7526817/use-of-instance-of-in-java) will tell how to use them, remind me to post as answer if it helps. or another way could be create a String with the same variable name and assign the it to the name of the class in both activities and check if they match.. – Elltz Jun 28 '15 at 23:07
  • Yes, you got it! `if (activity instanceof MainActivity) {...}` It worked just as I want, a bit compromise as I have to do if-else everywhere but its certainly better than try-catch. You solved a big problem for me. Thanks a lot! –  Jun 28 '15 at 23:13
  • You can post it as answer and I will be happy to mark it right. Cheers –  Jun 28 '15 at 23:13

1 Answers1

0

use instanceof

more info from the docs

Elltz
  • 10,730
  • 4
  • 31
  • 59