使用dagger2Dagger2子注入項目是空
修訂
我有電腦和waterpump類汽車類的簡單例子。我通過爲什麼電機中的子注入零件爲空來寫它們?
這是我的電機類與startEngin方法,檢查計算機和waterPump啓動。
public class Motor {
@Inject
public Computer computer;
@Inject
public WaterPump waterPump;
public Motor(){
}
// here computer and waterPump are null and not injected
public boolean startEngin(){
if(computer!=null && waterPump!=null){
return true;
}else{
return false;
}
}
}
,這是有型號和電壓計算機類:
public class Computer {
private int vultage;
private String model;
public Computer(String model ,int vultage){
this.model=model;
this.vultage = vultage;
}
}
,這是WaterPump:
public class WaterPump {
private String name;
public WaterPump(String name){
this.name = name;
}
}
這是我的模塊:
@Module
public class MotorModule {
Context context;
String motoName;
String computerName;
String waterPupName;
int voltage;
public MotorModule(Context context, String computerName, String waterPupName, int voltage) {
this.context = context;
this.waterPupName = waterPupName;
this.computerName = computerName;
this.voltage = voltage;
}
@Provides
@Singleton
Motor provideMotor() {
return new Motor();
}
@Provides
@Singleton
Computer provideComputer() {
return new Computer(computerName, voltage);
}
@Provides
@Singleton
WaterPump provideWaterPump() {
return new WaterPump(waterPupName);
}
@Provides
@Singleton
Context provideContext() {
return this.context;
}
}
這是我的組件類,我知道這一點沒有必要獲取Motor方法。
@Singleton
@Component(modules = {MotorModule.class})
public interface MotorComponent {
// Motor getMotor();
void inject(MainActivity activty);
,並在這裏活動注入電機爲空:
public class MainActivity extends AppCompatActivity {
@Inject
public Motor motor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerMotorComponent.builder().motorModule(new MotorModule
(this, "mahdi'PC", "my " +
"Water pump", 12)).build().inject(this);
if (motor.startEngin()) {
Toast.makeText(this, "it is started", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "motor is not provided", Toast.LENGTH_SHORT).show();
}
}
}
}
看http://stackoverflow.com/questions/31372901/android-dagger-2-dependency-not-being-injected和變化'注入(活動活動)''來注入(MainActivity mainActivity)'。您需要指定注射部位的編譯時類型 - '無效注射(活動活動)'將無法正常工作。 –
@DavidRawson OK現在汽車是不是空在您的幫助,但注射部位在汽車是零,而不是注射。 – Kenji