Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the main project class from a library class

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

like image 580
ssuperz28 Avatar asked Oct 31 '11 17:10

ssuperz28


1 Answers

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.

like image 178
CommonsWare Avatar answered Oct 09 '22 16:10

CommonsWare