A set of helper classes for using dagger 1 with Android components such as Applications, Activities, Fragments, BroadcastReceivers, and Services.

Overview

##fb-android-dagger

A set of helper classes for using dagger with Android components such as Applications, Activities, Fragments, BroadcastReceivers, and Services.

Maven users:

<dependency>
   <groupId>com.fizz-buzz</groupId>
   <artifactId>fb-android-dagger</artifactId>
   <version>1.0.6</version>
</dependency>

Note: this project's POM specifies dependencies for the Android SDK and the support v4 library using the group IDs, artifact IDs, and version numbers created by the [Maven Android SDK Deployer] (https://github.com/mosabua/maven-android-sdk-deployer), as opposed to the ones in Maven Central, which contains artifacts that are unofficial and out of date. If you want to use the ones in Maven Central anyway, just update those dependencies in the POM.

####Overview

fb-android-dagger provides a set of base classes for using dagger in Android applications. It follows a convention exemplified by Square's sample application, whereby a base class calls getModules() to gather the set of modules that its subclass(es) need to be part of the graph, then creates an object graph from those modules and injects itself.

The following classes are provided, each implementing this technique in the method indicated in parentheses:

  • InjectingApplication (onCreate)
  • InjectingBroadcastReceiver (onReceive)
  • InjectingAppWidgetProvider (onReceive)
  • InjectingService (onCreate)
  • InjectingActivity (onCreate)
  • InjectingActionBarActivity (onCreate)
  • InjectingFragmentActivity (onCreate)
  • InjectingPreferenceActivity (onCreate)
  • InjectingFragment (onAttach)
  • InjectingListFragment (onAttach)
  • InjectingDialogFragment (onAttach)

####The graphs

InjectingApplication creates an application-scope graph.

InjectingBroadcastReciever, InjectingAppWidgetProvider, InjectingService, and the various Injecting...Activity classes each extend the application-scope graph with their own module(s), resulting in a graph scoped to their own component.

The various Injecting...Fragment classes extend their corresponding activity's graph.

####Modules

Each component type has an associated module:

  • InjectingActivityModule
  • InjectingServiceModule
  • InjectingBroadcastRecieverModule
  • InjectingActivityModule
  • InjectingFragmentModule

The last two are shared by the Injecting...Activity classes and the Injecting...Fragment classes, respectively. These modules define provider methods which enable injection of objects relevant to their component type. They all have a provider that returns the component itself in the form of an Injector interface:

public interface Injector {
    public ObjectGraph getObjectGraph();
    public void inject(Object target);
}

Qualifier annotations defined in the various modules allow for specific components' injectors to be accessed:

class Foo1 {
    @Inject @Application Injector appInjector;
    @Inject @Activity Injector activityInjector;
    @Inject @Fragment Injector fragInjector;
    //...
}

Application and Activity Contexts are similarly accessible:

class Foo2 {
    @Inject @Application Context appContext;
    @Inject @Activity Context activityContext;
    // ...
}

...as are the typed components themselves:

class Foo3 {
    @Inject Application theApp;
    @Inject Activity myActivity;
    @Inject Fragment myFragment;
    // ...
}

####Developed by

Andy Dennie - [email protected]

####License

Copyright 2014 Fizz Buzz LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Comments
  • rotation causes NPE

    rotation causes NPE

    this appears to have the same cause as https://github.com/square/dagger/issues/227. onAttach on a fragment doesn't necessarily happen after onCreate of the activity when the activity is rebuilt on rotation, so the graph may not exist yet.

    opened by yincrash 3
  • How to create a fragment graph by extending the parent Fragment's graph?

    How to create a fragment graph by extending the parent Fragment's graph?

    I have make a reusable widget fragment that can be add into a activity or a fragment, but I dont know how to correctly inject things into this class as the object graph might come from its parent fragment or hosting activity.

    opened by mortyccp 1
  • Should InjectingFragment inject itself onActivityCreated instead?

    Should InjectingFragment inject itself onActivityCreated instead?

    Due to the fact that onAttach does not guarantee the Activity has finished its onCreate, so the activity object graph the injecting fragment get might be null. So I think it is not safe to inject dependency on onAttach method.

    opened by mortyccp 1
  • What about if i want to inject in a normal java class

    What about if i want to inject in a normal java class

    I have this project https://github.com/AmauryEsparza/ChatApplicationDagger and i need to inject dependencies out of Activities or any other Android component. As you can see in the project, i'm passing the Application reference through the classes for inject the instances but i think that was wrong, do you or any have an advice? Thank's

    opened by AmauryEsparza 1
  • Removed guava from runtime dependencies

    Removed guava from runtime dependencies

    I did 2 things:

    • changed android.version and android-support-v4.version to the latest versions found in the central repo
    • copied Preconditions.checkState to this project and removed guava from dependencies It is still there as a transitive compile dependency, but if clients don't depend on it themselves, their apk size just dropped by 2.2 MB. This should be notable in testing, because in ADT proguard isn't run for test apks.
    opened by JWahle 1
  • Adding custom code to onCreate in an Activity

    Adding custom code to onCreate in an Activity

    Hi,

    I'm new to Dagger and fb-android-dagger and was wondering if it is possible to use fb-android-dagger to inject custom code in an existing method in an Android Activity like onCreate. Is there a way to annotate an Activity to make this possible?

    Thanks!

    opened by n0k 2
  • InjectingActivity

    InjectingActivity

    Hey! First of all, loved the effort in making this lib. It sure helped me to understand Dagger a little better.

    My question is:

    Is there any way to extend your InjectingActivity without adding the specific classes to inject in the InjectingActivityModule? I would love to just extend your Activity and just run my app. Do I have to change the InjectingActivity to add something like this?

    @Module(injects = {MyActivity.class})
    
    opened by fabiocarballo 3
  • could not resolve support-v4

    could not resolve support-v4

    When including version 1.0.3 as a dependency from maven central using gradle, the build fails due to the following error: "Could not resolve all dependencies" "Could not find com.google.android:support-v4:r13"

    and it seems that the latest version of support-v4 on maven central is actually r7..

    opened by ghost 9
  • NoSuchMethodError: dagger.internal.ModuleAdapter.<init>

    NoSuchMethodError: dagger.internal.ModuleAdapter.

    I'm attempting to use fb-android-dagger and am running in to some trouble. I created a barebones project in order to show the problem and have posted it here:

    https://dl.dropboxusercontent.com/u/99107327/MyApplication.tar.gz

    I have tried removing the entries in includes, modifying injects to inject MainActivity.class itself. I'm not sure what else to try. Ultimately I would like to get a Context from InjectingActivityModule's provideActivityContext method, but at this point I'm stuck with the NoSuchMethodError.

    I am using Dagger 1.2.1 and fb-android-dagger 1.0.1 and I'm running Android 4.4.2 on a Nexus 4 (Dalvik).

    The stacktrace:

    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app I/dalvikvm﹕ Could not find method dagger.internal.ModuleAdapter.<init>, referenced from method com.fizzbuzz.android.dagger.InjectingApplication$InjectingApplicationModule$$ModuleAdapter.<init>
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app W/dalvikvm﹕ VFY: unable to resolve direct method 16223: Ldagger/internal/ModuleAdapter;.<init> ([Ljava/lang/String;[Ljava/lang/Class;Z[Ljava/lang/Class;ZZ)V
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app D/dalvikvm﹕ VFY: replacing opcode 0x76 at 0x000a
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app D/dalvikvm﹕ DexOpt: couldn't find field Lcom/fizzbuzz/android/dagger/InjectingApplication$InjectingApplicationModule$$ModuleAdapter;.module
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app W/dalvikvm﹕ VFY: unable to resolve instance field 636
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app D/dalvikvm﹕ VFY: replacing opcode 0x54 at 0x0004
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app D/dalvikvm﹕ DexOpt: couldn't find field Lcom/fizzbuzz/android/dagger/InjectingApplication$InjectingApplicationModule$$ModuleAdapter;.module
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app I/dalvikvm﹕ DexOpt: unable to optimize instance field ref 0x027c at 0x12 in Lcom/fizzbuzz/android/dagger/InjectingApplication$InjectingApplicationModule$$ModuleAdapter;.getBindings
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app D/dalvikvm﹕ DexOpt: couldn't find field Lcom/fizzbuzz/android/dagger/InjectingApplication$InjectingApplicationModule$$ModuleAdapter;.module
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app I/dalvikvm﹕ DexOpt: unable to optimize instance field ref 0x027c at 0x20 in Lcom/fizzbuzz/android/dagger/InjectingApplication$InjectingApplicationModule$$ModuleAdapter;.getBindings
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app D/AndroidRuntime﹕ Shutting down VM
    03-10 11:04:00.126  11985-11985/com.example.myapplication3.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415a9ba8)
    03-10 10:59:23.490  11677-11677/com.example.myapplication3.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.example.myapplication3.app, PID: 11677
        java.lang.NoSuchMethodError: dagger.internal.ModuleAdapter.<init>
                at com.fizzbuzz.android.dagger.InjectingApplication$InjectingApplicationModule$$ModuleAdapter.<init>(InjectingApplication$InjectingApplicationModule$$ModuleAdapter.java:20)
                at java.lang.Class.newInstanceImpl(Native Method)
                at java.lang.Class.newInstance(Class.java:1208)
                at dagger.internal.Loader.instantiate(Loader.java:84)
                at dagger.internal.FailoverLoader$1.create(FailoverLoader.java:42)
                at dagger.internal.FailoverLoader$1.create(FailoverLoader.java:40)
                at dagger.internal.Memoizer.get(Memoizer.java:56)
                at dagger.internal.FailoverLoader.getModuleAdapter(FailoverLoader.java:57)
                at dagger.internal.Modules.loadModules(Modules.java:43)
                at dagger.ObjectGraph$DaggerObjectGraph.makeGraph(ObjectGraph.java:174)
                at dagger.ObjectGraph$DaggerObjectGraph.access$000(ObjectGraph.java:138)
                at dagger.ObjectGraph.create(ObjectGraph.java:129)
                at com.fizzbuzz.android.dagger.InjectingApplication.onCreate(InjectingApplication.java:57)
                at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4344)
                at android.app.ActivityThread.access$1500(ActivityThread.java:135)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:136)
                at android.app.ActivityThread.main(ActivityThread.java:5017)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                at dalvik.system.NativeStart.main(Native Method)
    
    opened by dpkirchner 2
Releases(1.0.7)
  • 1.0.7(Oct 9, 2015)

  • 1.0.6(Jan 16, 2015)

    This release includes two new injecting base classes:

    • InjectingAppWidgetProvider
    • InjectingActionBarActivity

    In addition, InjectingApplication was enhanced with new addSeedModules() method to facilitate unit testing with test-method-specific dagger modules. See http://andydennie.com/2014/12/16/initialize-your-android-components-dagger-object-graph-on-a-per-method-basis-in-your-robolectric-tests/ for a detailed explanation of how to use this feature.

    Finally, InjectingServiceModule's provideApplicationContext() provider method was replaced with provideServiceContext, which seems to make more sense in that, uh... context.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.5(Nov 10, 2014)

    New in this release:

    • update dagger dependency to version 1.2.1
    • copy needed bits from Guava and remove the Guava dependency, reducing the library size considerably (contributed by Tobias Preuss)
    • modify Android and support v4 dependencies to use the group IDs, artifact IDs, and version IDs created by the Maven Android SDK Deployer.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.3(Apr 15, 2014)

  • 1.0.2(Apr 14, 2014)

    This release tweaks the handling of configuration changes (e.g. orientation changes).

    Previously, InjectingActivity's onCreate method didn't set up its graph or inject itself until after calling super.onCreate. Since that call to super.onCreate would trigger a call to a retained InjectingFragment's onAttach method, when that InjectingFragment tried to extend the activity graph, it would generate an NPE due to the activity graph not being initialized yet.

    In this release, InjectingActivity initializes its graph an injects itself before calling super.onCreate.

    Source code(tar.gz)
    Source code(zip)
Owner
Andy Dennie
Andy Dennie
Type safe intent building for services and activities

#IntentBuilder Type safe intent building for services and activities. IntentBuilder is a type safe way of creating intents and populating them with ex

Emil Sjölander 348 Oct 10, 2022
A beautiful set of predefined colors and a set of color methods to make your Android development life easier.

Colours is a port of the Colours Library for iOS made by my good friend Ben Gordon. You can find that project here. Installation Maven Central Colours

Matthew York 634 Dec 28, 2022
Generate helper methods for compose navigation using KSP

Compose NavGen Generate helper methods for compose navigation using KSP. ?? You can try it now, but it's still under development. ?? TODO Support defa

Kenji Abe 6 Feb 5, 2022
XClipper is a clipboard manager for Windows & Android which helps to track clipboard activities and makes it easier to interact with them.

XClipper XClipper is a clipboard manager for Windows & Android which helps to track clipboard activities and makes it easier to interact with them ❤️

Kaustubh Patange 134 Dec 31, 2022
A helper library to ease the most repetitive codes with simple reusable attributes.

ak-universal-android-helper A helper library to ease the most repetitive codes with simple reusable attributes. AKUAH can help you with many repetitiv

Aakash Kumar 20 Jul 8, 2020
Item Helper For Kotlin

Item Helper For Kotlin

Blugon 2 Dec 3, 2021
CreditCardHelper 🖊️ A Jetpack-Compose library providing useful credit card utilities such as card type recognition and TextField ViewTransformations

CreditCardHelper ??️ A Jetpack-Compose library providing useful credit card utilities such as card type recognition and TextField ViewTransformations

Stelios Papamichail 18 Dec 19, 2022
A support library for VectorDrawable and AnimatedVectorDrawable classes introduced in Lollipop

vector-compat A support library for VectorDrawable and AnimatedVectorDrawable introduced in Lollipop with fully backwards compatible tint support (api

Wael N 1.2k Nov 29, 2022
FractalUtils - A collection of utility functions and classes, with an emphasis on game related utilities

A collection of utility functions and classes written in Kotlin. There is some emphasis on utilities useful for games (Geometry, Random, Time, Updating, etc).

null 2 Nov 11, 2022
A dual screen capable home screen launcher for Android phones with dual displays, such as the LG V60, G8X & Velvet.

Duality-Launcher A dual screen capable home screen launcher for Android phones with dual displays, such as the LG V60, G8X & Velvet

Russ Nash 6 Sep 8, 2022
Utility library that utilizes KSP to generate Room type converter classes.

Roomie Roomie is an annotation processing library that utilizes KSP to geaRoomie is an annotation processing library that utilizes KSP to generate TypeConverter classes for Room. TypeConverter classes most often involve same boiler-plate code and Roomie makes it really easy to quickly create them with a single annotation.nerate TypeConverter classes for Room. TypeConverter classes most often invol

Chukwuka Eze 12 Aug 26, 2022
Access and process various types of personal data in Android with a set of easy, uniform, and privacy-friendly APIs.

PrivacyStreams PrivacyStreams is an Android library for easy and privacy-friendly personal data access and processing. It offers a functional programm

null 269 Dec 1, 2022
Matches incoming and/or outgoing text messages against set rules and sends them over to webhook.

Textmatic If you ever wanted a tool to simply push the SMS (or text messages) from your phone to somewhere remote, this is it. This app matches all in

Float 2 Jan 7, 2022
Dagger Hilt, MVP Moxy, Retrofit, Kotlin coroutine, Sealed class

Dagger Hilt, MVP Moxy, Retrofit, Kotlin coroutine, Sealed class

Dostonjon 1 Nov 2, 2021
A set of lint rules to check for common mistakes when styling and theming on Android

A set of lint rules to check for common mistakes when styling and theming on Android

GuilhE 6 Aug 29, 2022
DiskCache - Simple and readable disk cache for kotlin and android applications

DiskCache Simple and readable disk cache for kotlin and android applications (with journaled lru strategy) This is a simple lru disk cache, based on t

Giovanni Corte 14 Dec 2, 2022
compaKTset is a small library aimed at providing you with the most memory efficient Set implementation for any particular data type of your choosing.

compaKTset is a small library aimed at providing you with the most memory efficient Set implementation for any particular data type of your choosing.

Ignat Beresnev 3 Nov 16, 2021
KDoctor - A command-line tool that helps to set up the environment for Kotlin Multiplatform Mobile app development

KDoctor is a command-line tool that helps to set up the environment for Kotlin Multiplatform Mobile app development.

Kotlin 331 Dec 29, 2022
A Virtual Machine For Assessing Android applications, Reverse Engineering and Malware Analysis

Androl4b AndroL4b is an android security virtual machine based on ubuntu-mate includes the collection of latest framework, tutorials and labs from dif

null 1k Dec 27, 2022