6

I have an Android project that uses a library project (all of which I built). I am using ADT/SDK v14 and I need to access the main class in the main project and call a function when a dialog in the library project is dismissed. Now, I can do that if I add a reference to my main project to the library project, but that isn't ideal. How do I get a reference to a class in my main project from a class in the library project?

This is how it's working:

  • I have my main class in my project that is a tabhost
  • The tabhost gets the fragments for the tabs from the library project
  • One of the fragments for the tabs launches a DialogFragment
  • When that DialogFragment is dismissed, I need to call a fillItems() function in the main class(this is where I'm stuck)

Anyone have any ideas?

Thanks, Ed

ssuperz28
  • 1,834
  • 1
  • 14
  • 23
  • 1
    From an OOP perspective, you shouldn't be communicating that way. You don't want your libraries tightly coupled to your main projects; they'll quickly become "un-share-able." – Austin Salonen Oct 31 '11 at 17:23
  • Yeah, I knew that wasn't the way to go and I was trying to avoid it, but I just couldn't wrap my head around what I need to do. The answer below was what I need to get by it. Thanks. – ssuperz28 Oct 31 '11 at 19:38

1 Answers1

5

How do I get a reference to a class in my main project from a class in the library project?

Ideally, you don't.

Instead, you:

  1. Define an interface in the library that contains the methods you want to invoke whose implementation comes from the main project
  2. Implement that interface on some likely class in your main project
  3. Supply that implementation to the library via some setter or via a constructor argument
  4. Have the library call the methods on the interface implementation as needed
  5. Make sure you aren't introducing any sort of garbage collection problems by doing all of this

The only way to literally "get a reference to a class in my main project from a class in the library project" is via reflection, which is slow and makes for difficult-to-maintain code.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you! I knew I was overthinking this. Building on what you said above, I created a global listener in the library and subscribe to it in my main class and now I'm able to call my function. I don't think there would be any GC issues with that, right? Seems pretty efficient. I use your samples all the time, they have helped me out of a few dilemas. Thanks! – ssuperz28 Oct 31 '11 at 19:42
  • @ssuperz28: "I don't think there would be any GC issues with that, right?" -- I have no way to tell, sorry. – CommonsWare Oct 31 '11 at 19:45