1

我是 Koin 的新手(通常我使用 Dagger),现在我无法使用 MVP 将我的 View 实例传递给 Presenter。我遇到了 NullPointer 异常。如何将视图实例传递给我的演示者?它看起来像 Koin 在 View 上传递 null (在 Dagger 中我将使用contributeActivityInjection

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
        at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
        at com.strangelove.dtfu.MainActivity._$_findCachedViewById(Unknown Source:25)
        at com.strangelove.dtfu.MainActivity.showText(MainActivity.kt:10)
        at com.strangelove.dtfu.MySimplePresenter.sayHelloFromActivity(MySimplePresenter.kt:7)
        at com.strangelove.dtfu.MainActivity.onCreate(MainActivity.kt:19)

主持人

class MySimplePresenter(private val repo: HelloRepository, private val mainActivityView: MainActivityView) {
    fun sayHello() = "${repo.giveHello()} from $this"

    fun sayHelloFromActivity() {
        mainActivityView.showText(sayHello())
    }
}

活动

class MainActivity : AppCompatActivity(), MainActivityView {
    override fun showText(text: String) {
        first_textView.text = firstPresenter.sayHello()
    }

    private val firstPresenter: MySimplePresenter by inject()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onStart() {
        super.onStart()
        firstPresenter.sayHelloFromActivity()
    }
}

看法

interface MainActivityView {
    fun showText(text: String)
}

模块

val appModule = module {
    single<HelloRepository> {
        HelloRepositoryImpl()
    }

    factory {
        MySimplePresenter(get(), get())
    }
}

val activityModule = module {
    single<MainActivityView> {
        MainActivity()
    }
}

应用:

class MyApplication: Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin {
            androidLogger()
            androidContext(this@MyApplication)
            modules(appModule, activityModule)
        }
    }
}
4

1 回答 1

1

尝试改变

factory {
    MySimplePresenter(get(), get())
}

factory { (view: MainActivityView) ->
    MySimplePresenter(get(), view)
}

在活动中:

private val firstPresenter: MySimplePresenter by inject { parametersOf(this@MainActivity) }

通过这种方式,您提供了一种观点作为论据,我相信这在这种情况下是可取的。

于 2019-04-25T11:23:39.230 回答