Injecting my module in Dagger gives me NPE

110 Views Asked by At

Im trying to implement a simple example with Dagger where Module returns just a string

Module is :

@Module(
    injects = { MainActivity.class }
)
 public class MyDataModule {

public MyDataModule() {
}

@Provides
public MyDataModule provideMyData() {
    return new MyDataModule();
}


public String createMyDataItems() {
    return "MyDataString";
}

}

And Activity :

@Inject MyDataModule myDataModule;

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.my_data);
    textView.setText(myDataModule.createMyDataItems());

}

}

And I get a NPE at the last line :

textView.setText(myDataModule.createMyDataItems());
1

There are 1 best solutions below

0
On

You need to instantiate the object graph with

ObjectGraph.create(new MyDataModule())

You can read more in the official tutorial.

As a side note, I recommend you try setting up Dagger 2 instead of Dagger 1