使用匕首2注入构造函数演示者后,视图变为null

时间:2019-06-28 07:11:08

标签: android retrofit2 dagger-2 android-mvp

你好,我是匕首2的新手。当我在下面运行代码时,我得到了:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

Unable to start activity ComponentInfo{com.ali.daggerplayground/com.ali.daggerplayground.main.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

当我不使用匕首时,此代码运行良好。我不明白是什么使视图变为空。也许有人可以给我解释一下吗?

这是我的活动。

class MainActivity : BaseActivity(), MainContract.View {

@Inject
internal lateinit var mPresenter: MainContract.Presenter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    App.main.inject(this)
    tv.text = "This Button"
    mPresenter.attach(this)
    mPresenter.getImage()
}

override fun onSuccess(message: String?) {
    Log.i("MessageReturn", message)
    tv.text = message
}

这是我的演示者:

class MainPresenter @Inject constructor(private val mView: MainContract.View) :
    MainContract.Presenter {

override fun attach(view: MainContract.View) {

}

override fun getImage() {
    mView.onSuccess("success")
}

这是我的模块:

@Module
class ModuleMain {

@Provides
@Singleton
fun provideMainPresenter(mainView: MainContract.View): MainContract.Presenter {
    return MainPresenter(mainView)
}

@Provides
@Singleton
fun provideMainView(): MainContract.View {
    return MainActivity()
}

此组件:

@Singleton
@Component(modules = [ModuleMain::class, ModuleNetwork::class])
interface ComponentMain {

fun inject(mainActivity: MainActivity)

@Component.Builder
interface Builder {

    @BindsInstance
    fun application(application: Application): Builder

    fun moduleNetwork(moduleNetwork: ModuleNetwork): Builder
    fun build(): ComponentMain
}

1 个答案:

答案 0 :(得分:2)

据我所知,您的ModuleMain是不正确的,因为您不应该在该模块中提供视图,请像这样更改它

@Module
class ModuleMain {

  @Provides
  @Singleton
  fun provideMainPresenter(): MainContract.Presenter {
    return MainPresenter()
  }
}

当然,MainPresenter应该看起来像这样

class MainPresenter @Inject constructor() :
    MainContract.Presenter {

  override fun attach(view: MainContract.View) {
    mView = view
  }
}