einfaches Beispiel für die Verwendung von dagger2Dagger2 Unter injiziert Artikel ist null
AKTUALISIERT
ich einen Motor Klasse, die Computer-und Wasserstrahl Klasse. Ich schreibe sie so, warum sub injizierte Teile in Motor null ist?
Dies ist meine Motorklasse mit StartEngin Methode, die Computer und Wasserpumpe zu starten.
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;
}
}
}
und das ist Klasse-Computer, der Modellname und Spannung haben:
public class Computer {
private int vultage;
private String model;
public Computer(String model ,int vultage){
this.model=model;
this.vultage = vultage;
}
}
und das ist Wasserpumpenrad:
public class WaterPump {
private String name;
public WaterPump(String name){
this.name = name;
}
}
das ist mein Modul:
@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;
}
}
und das ist meine Komponente Klasse, das weiß ich es gibt keine Notwendigkeit, Motor-Methode zu bekommen.
@Singleton
@Component(modules = {MotorModule.class})
public interface MotorComponent {
// Motor getMotor();
void inject(MainActivity activty);
und hier in Aktivität injiziert Motor null ist:
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();
}
}
}
}
siehe http://stackoverflow.com/questions/31372901/android-dagger-2-dependency-not-being-injected und ändere 'inject (Aktivitätsaktivität)' in 'inject (MainActivity mainActivity)'. Sie müssen den Kompilierungszeittyp der Injektionsstelle angeben - "void inject (Aktivitätsaktivität)" wird nicht funktionieren. –
@DavidRawson ok jetzt Motor ist nicht null mit Ihrer Hilfe, aber injizierte Teile in Motor ist null und nicht injiziert. – Kenji