带有匕首和房间的多个活动中的依赖注入

时间:2019-07-15 11:37:05

标签: android dependency-injection android-room dagger

我是来自C#的Android初学者,遇到了使用匕首进行依赖注入的情况。我设法创建了一个简单的示例,但想知道如何在另一个活动中使用我的存储库(我试图在这里使用存储库模式)。所以我的结构如下: Project structure 当我尝试在MainActivity类中创建锻炼时,效果很好。所以我在我的AddWorkoutActivity类中添加了以下行

@Inject
public WorkoutRepository workoutRepository;

但是,当我尝试保存锻炼时,我在executionRepository上总是会收到空参考错误,因此我在理解DI在这里的工作方式时确实错过了一些东西。也许有人可以给我一个提示,我必须做些什么,以便在我的Activity中以正确的方式实例化我的存储库。

//编辑: 我认为问题在于我在MainActivity类的onCreate方法中调用了DaggerAppComponent.builder()...,因此AddWorkoutActivity对此一无所知。但是,我该在哪里初始化DaggerAppComponent以便两个活动都能正确访问它?

最诚挚的问候

应用程序组件:

package jh.projects.wodm8.di;

import android.app.Application;
import javax.inject.Singleton;
import dagger.Component;
import jh.projects.wodm8.view.MainActivity;
import jh.projects.wodm8.data.WorkoutDao;
import jh.projects.wodm8.repository.DemoDatabase;
import jh.projects.wodm8.repository.WorkoutRepository;

@Singleton
@Component(modules = {AppModule.class, RoomModule.class})
public interface AppComponent {

void inject(MainActivity mainActivity);

WorkoutDao workoutDao();

DemoDatabase demoDatabase();

WorkoutRepository productRepository();

Application application();
}

AppModule

package jh.projects.wodm8.di;

import android.app.Application;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;

@Module
public class AppModule {

    Application mApplication;

    public AppModule(Application application) {
        mApplication = application;
    }

    @Provides
    @Singleton
    Application providesApplication() {
        return mApplication;
    }
}

RoomModule

package jh.projects.wodm8.di;

import android.app.Application;

import androidx.room.Room;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import jh.projects.wodm8.data.WorkoutDao;
import jh.projects.wodm8.repository.DemoDatabase;
import jh.projects.wodm8.repository.WorkoutDataSource;
import jh.projects.wodm8.repository.WorkoutRepository;

@Module
public class RoomModule{

    private DemoDatabase demoDatabase;

    public RoomModule(Application mApplication) {
        demoDatabase = Room.databaseBuilder(mApplication, DemoDatabase.class, "demo-db").allowMainThreadQueries().build();
    }

    @Singleton
    @Provides
    DemoDatabase providesRoomDatabase() {
        return demoDatabase;
    }

    @Singleton
    @Provides
    WorkoutDao providesWorkoutDao(DemoDatabase demoDatabase) {
        return demoDatabase.getWorkoutDao();
    }

    @Singleton
    @Provides
    WorkoutRepository providesWorkoutRepository(WorkoutDao workoutDao) {
        return new WorkoutDataSource(workoutDao);
    }
}

WorkoutDataSource

package jh.projects.wodm8.repository;

import androidx.lifecycle.LiveData;

import java.util.List;

import javax.inject.Inject;

import jh.projects.wodm8.data.Workout;
import jh.projects.wodm8.data.WorkoutDao;

public class WorkoutDataSource implements WorkoutRepository {

    private WorkoutDao workoutDao;

    @Inject
    public WorkoutDataSource(WorkoutDao workoutDao) {
        this.workoutDao = workoutDao;
    }

    @Override
    public LiveData<Workout> findById(int id) {
        return workoutDao.findById(id);
    }

    @Override
    public LiveData<List<Workout>> findAll() {
        return workoutDao.findAll();
    }

    @Override
    public void insert(Workout workout) {
        workoutDao.insert(workout);
    }

    @Override
    public int delete(Workout workout) {
        return workoutDao.delete(workout);
    }
}

WorkoutRepository

package jh.projects.wodm8.repository;

import androidx.lifecycle.LiveData;

import java.util.List;

import jh.projects.wodm8.data.Workout;

public interface WorkoutRepository {
    LiveData<Workout> findById(int id);

    LiveData<List<Workout>> findAll();

    void insert(Workout workout);

    int delete(Workout workout);

}

MainActivity     包jh.projects.wodm8.view;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

import javax.inject.Inject;

import jh.projects.wodm8.R;
import jh.projects.wodm8.data.Workout;
import jh.projects.wodm8.di.AppModule;
import jh.projects.wodm8.di.DaggerAppComponent;
import jh.projects.wodm8.di.RoomModule;
import jh.projects.wodm8.repository.WorkoutRepository;

public class MainActivity extends AppCompatActivity {

    @Inject
    public WorkoutRepository workoutRepository;

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

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), AddWorkoutActivity.class);
                startActivity(intent);
            }
        });

        DaggerAppComponent.builder()
                .appModule(new AppModule(getApplication()))
                .roomModule(new RoomModule(getApplication()))
                .build()
                .inject(this);

        workoutRepository.findAll().observe(this, new Observer<List<Workout>>() {
            @Override
            public void onChanged(@Nullable List<Workout> products) {
                Toast.makeText(MainActivity.this, String.format("Product size: %s", products.size()), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

AddWorkoutActivity

package jh.projects.wodm8.view;

import androidx.appcompat.app.AppCompatActivity;

import jh.projects.wodm8.R;
import jh.projects.wodm8.data.Workout;
import jh.projects.wodm8.di.AppModule;
import jh.projects.wodm8.di.DaggerAppComponent;
import jh.projects.wodm8.di.RoomModule;
import jh.projects.wodm8.repository.DemoDatabase;
import jh.projects.wodm8.repository.WorkoutRepository;

import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import javax.inject.Inject;

public class AddWorkoutActivity extends AppCompatActivity {

    @Inject
    public WorkoutRepository workoutRepository;

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

        final Button button = findViewById(R.id.saveWorkout);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Workout workout = new Workout();
                EditText txtTitle = (EditText) findViewById(R.id.workoutTitleText);
                workout.setTitle(txtTitle.getText().toString());

                try {
                    workoutRepository.insert(workout);
                } catch (Exception e) {
                    Log.v("AddWorkout", e.getMessage());
                }

                Toast.makeText(AddWorkoutActivity.this, "Inserted", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

从此在线资源https://github.com/MindorksOpenSource/android-dagger2-example/blob/master/app/src/main/java/com/mindorks/example/android_dagger2_example/DemoApplication.java

中获取更多更完整的答案

(我只是简要介绍一下,以使您更好地理解)

创建一个扩展Application的应用程序类并实现它:

     @Override
     public void onCreate() {
        super.onCreate();
        applicationComponent = DaggerApplicationComponent
                                    .builder()
                                    .applicationModule(new ApplicationModule(this))
                                    .build();
        applicationComponent.inject(this);
}

尽管如此,您必须定义自己的applicationComponent。 之后,您应该可以在需要使用注解的@Inject的几个不同位置使用存储库,只需记住在需要的地方实际调用注入,即使用

getActivityComponent().inject(this);AndroidInjection.inject(this),希望这个github示例和教程足以回答您的一些问题