Best way to declare Fragment dependencies for test- and readability? [on hold]

189
January 25, 2018, at 00:19 AM

Basically there are two ways which i know of:

  • Pass the dependency through newInstance
  • Retrieve the depencency through onAttach

Both methods seem to get the job done.

However the first method, is very much like the usual way of declaring dependencies through a constructor, but it requires the passed dependency to implement the Parcelable interface, which is not always possible, or wanted. (eg. database DAO and repository)

The second method retrieves the dependencies when it gets attach to a context. This way it's possible to ask the context if it has, certain dependencies needed for the fragment to function. It seems like a very clean and efficient way, but the problem with this is it hides dependencies, and makes it harder to test.

So my question is this: Is there a third way? Or is there some way to make either method have the best of both worlds?

Answer 1

You can use Dagger 2 to inject dependencies into your fragment. After you have set it up, you can just annotate a member of your fragment with the @Inject annotation and Dagger 2 will provide an instance of a required class. And it's possible to replace your dependencies in tests.

Rent Charter Buses Company
READ ALSO
Service and DAO classes in JAVA

Service and DAO classes in JAVA

I have 3 DAO and service classes for project, customer, and issuesI have one more jiraService class in which I use the JIRA API

233
Sending Request from Angular to Java Servlet

Sending Request from Angular to Java Servlet

I have an angular app and a java servlet backendwhat I need to do is send httpRequest from angular to backend

248
unlimited cursor Mongo DB for java

unlimited cursor Mongo DB for java

I'm traying to all the document with this aggregate query but the problem here that the cursor is limited , he return approximitly 500 resultsI tried with limit(0)but it doesn't work ! , also i tried with limit(10000) or limit (20000) but it's doesn't...

196
Why java String treat some UTF-8 symbols as several characters

Why java String treat some UTF-8 symbols as several characters

I'm trying to cover utf-8 symbols but java String converts 1 symbol to several sometimesWriting it to file and displaying in editor works well, but I need to check valid java identifiers which can be written even in 4 bytes like "f0 93 81 98" for next diapason:

277