如何修复MainActivity? kotlin.UninitializedPropertyAccessException:lateinit属性CompositeDiposable尚未初始化

时间:2019-04-13 19:13:49

标签: java android kotlin rx-java retrofit2

我遇到的错误是“ java.lang.RuntimeException:无法启动活动ComponentInfo {com.ginem.rxjavaandretrofit2demo / com.ginem.rxjavaandretrofit2demo.MainActivity}:kotlin.UninitializedPropertyAccessException:lateinit属性CompositeDiposable尚未初始化 ” 这是在应用程序完成后发生的,并试图在我的android虚拟机中启动。

我正在创建一个ororid应用,该应用从伪造的REST Api中提取数据,并使用RxJava和Retrofit2以cardview / recyclerview格式显示数据。

到目前为止,我已经尝试将依赖项版本更改为较低版本,但仍然没有成功。我还添加了列出的所有kotlin插件:

应用插件:“ kotlin-android”

应用插件:“ kotlin-android-extensions”

应用插件:“ kotlin-kapt”

package com.ginem.rxjavaandretrofit2demo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.ginem.rxjavaandretrofit2demo.Adapter.PostAdapter
import com.ginem.rxjavaandretrofit2demo.Model.Post
import com.ginem.rxjavaandretrofit2demo.Retrofit.IMyAPI
import com.ginem.rxjavaandretrofit2demo.Retrofit.RetrofitClient
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

  internal lateinit var jsonApi:IMyAPI
  internal lateinit var compositeDiposable: CompositeDisposable

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


    // init API
    val retrofit = RetrofitClient.instance
    jsonApi = retrofit.create(IMyAPI::class.java)

    //View
    recycler_posts.setHasFixedSize(true)
    recycler_posts.layoutManager=LinearLayoutManager(this)
    fetchData()
}

private fun fetchData() {
    compositeDiposable.add(jsonApi.posts
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe{posts->displayData(posts)})
}

private fun displayData(posts: List<Post>?) {

    val adapter = PostAdapter(this, posts!!)
    recycler_posts.adapter = adapter
 }

}

Model:App(build.gradle)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
   compileSdkVersion 28
   defaultConfig {
    applicationId "com.ginem.rxjavaandretrofit2demo"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner 
     "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android- 
        optimize.txt'), 'proguard-rules.pro'
    }
   }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib- 
    jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

//Retrofit2
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

//RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.7'


//Support
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

}

IMyAPI接口

package com.ginem.rxjavaandretrofit2demo.Retrofit

import com.ginem.rxjavaandretrofit2demo.Model.Post 
import io.reactivex.Observable
import retrofit2.http.GET

interface IMyAPI {

   @get: GET("posts")
   val posts: Observable<List<Post>>
}

RetrofitClient类

package com.ginem.rxjavaandretrofit2demo.Retrofit

import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClient {

  private var ourInstance: Retrofit? = null

  val instance:Retrofit
  get() {
      if(ourInstance == null){
          ourInstance = Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com")
            .addConverterFactory(GsonConverterFactory.create())

 .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
             .build()
    }
    return ourInstance!!
 }
}

2 个答案:

答案 0 :(得分:1)

问题恰恰是错误消息所说的。在调用add()之前,我看不到实际设置CompositeDisposable的任何地方。那时它仍然为空。您需要使用CompositeDisposable = ...对其进行初始化,更改为输入参数,并使用依赖项注入框架。

答案 1 :(得分:0)

正如您所说的Dean,我已设置为null。解决我简单添加的问题

internal  var compositeDisposable: CompositeDisposable = CompositeDisposable();

它运行得很好。