【问题标题】:when init Retrofit I get error: KotlinNullPointerException当初始化改造我得到错误:KotlinNullPointerException
【发布时间】:2019-11-08 11:35:24
【问题描述】:
class TransportService {
    companion object {
        private val waitressCallRestClient =  RestClientFactory.createRestClient(WaitressCallRestClient::class.java)

        private val TAG = TransportService::class.java.name

        init {
            Debug.d(TAG, "TransportService_initialize")
       }
    }
}

这里是 RestClientFactory.kt

object RestClientFactory {
    private val gsonBuilder = GsonUtil.gsonbuilder
    var gson: Gson? = null
        private set
    private val CONNECTION_TIME_OUT_SEC = 60
    private val READ_TIME_OUT_SEC = 60
    private val WRITE_TIME_OUT_SEC = 60
    private var httpClient: OkHttpClient.Builder? = null
    private val httpLoggingInterceptor = HttpLoggingInterceptor()
        .setLevel(HttpLoggingInterceptor.Level.BODY)

    private val TAG = RestClientFactory::class.java.name

    private val builder = Retrofit.Builder()
        .baseUrl(BuildConfig.API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson!!))
        .addConverterFactory(QueryConverterFactory.create())
        .client(httpClient!!.build())

    var retrofit = builder.build()
        private set



    fun <T> createRestClient(restClientClass: Class<T>): T {
        retrofit = builder.build()
        return retrofit.create(restClientClass)
    }
}

但我在这一行遇到运行时错误:

.addConverterFactory(GsonConverterFactory.create(gson!!))

错误:

11-08 13:26:58.104 E/AndroidRuntime(13653): FATAL EXCEPTION: main
11-08 13:26:58.104 E/AndroidRuntime(13653): Process: com.myproject.android.debug, PID: 13653
11-08 13:26:58.104 E/AndroidRuntime(13653): java.lang.ExceptionInInitializerError
11-08 13:26:58.104 E/AndroidRuntime(13653):     at com.myproject.android.service.TransportService.<clinit>(TransportService.kt:25)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at com.myproject.android.viewmodel.FeedbackViewModel$doClickSend$1.invokeSuspend(FeedbackViewModel.kt:39)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at android.os.Handler.handleCallback(Handler.java:739)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at android.os.Looper.loop(Looper.java:148)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at android.app.ActivityThread.main(ActivityThread.java:5417)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at java.lang.reflect.Method.invoke(Native Method)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-08 13:26:58.104 E/AndroidRuntime(13653):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-08 13:26:58.104 E/AndroidRuntime(13653): Caused by: kotlin.KotlinNullPointerException
11-08 13:26:58.104 E/AndroidRuntime(13653):     at com.myproject.android.api.RestClientFactory.<clinit>(RestClientFactory.kt:40)
11-08 13:26:58.104 E/AndroidRuntime(13653):     ... 11 more

【问题讨论】:

  • 您的 var gson 为 null 并且从未分配给您,并且您执行了不安全的非 null 强制转换 gson!!
  • 你忘记初始化gson var gson: Gson? = null

标签: android kotlin retrofit2


【解决方案1】:

httpClientgson 为空,你永远不会初始化它们。

停止使用!!,编译器会告诉你;)

【讨论】:

    【解决方案2】:
       1) try using this, If you do not want to use gson in this class
    
            private var retrofit: Retrofit? = null
             retrofit = Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            .client(httpClient.build())
                            .addConverterFactory(GsonConverterFactory.create())
                            .build()
    
        2) or if you want to use gson here then below code may help you :
        Gson gson = new GsonBuilder()
             .registerTypeAdapter(Id.class, new IdTypeAdapter())
             .enableComplexMapKeySerialization()
             .serializeNulls()
             .setDateFormat(DateFormat.LONG)
             .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
             .setPrettyPrinting()
             .setVersion(1.0)
             .create();
            Retrofit retrofit = new Retrofit.Builder()  
             .baseUrl(BASE_URL)
             .addConverterFactory(GsonConverterFactory.create(gson))
             .build();
    

    【讨论】:

      【解决方案3】:

      你需要初始化 Gson 对象。

      Gson gson = new GsonBuilder()
                      .setLenient()
                      .create();
      

      【讨论】:

        【解决方案4】:

        我改成这个,现在开始工作了:

        object RestClientFactory {
            private val gsonBuilder = GsonUtil.gsonbuilder
            private var gson: Gson
            private val CONNECTION_TIME_OUT_SEC = 60
            private val READ_TIME_OUT_SEC = 60
            private val WRITE_TIME_OUT_SEC = 60
            private var httpClient: OkHttpClient.Builder
            private val httpLoggingInterceptor =
                HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
        
            private val TAG = RestClientFactory::class.java.name
        
            init {
                Debug.d(TAG, "static_initializer: START_GSON_setting!")
                gson = gsonBuilder.create();
                gsonBuilder.setDateFormat(DateUtil.TO_FO_DATETIME_FORMAT)
                // default timeout = 10 sec
                httpClient = OkHttpClient.Builder() // default timeout = 10 sec
                    .connectTimeout(CONNECTION_TIME_OUT_SEC.toLong(), TimeUnit.SECONDS)
                    .readTimeout(READ_TIME_OUT_SEC.toLong(), TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIME_OUT_SEC.toLong(), TimeUnit.SECONDS)
        

        【讨论】:

          【解决方案5】:

          替换

          .addConverterFactory(GsonConverterFactory.create(gson!!))
          

          .addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-06-05
            • 1970-01-01
            • 1970-01-01
            • 2020-02-17
            • 2012-03-29
            • 1970-01-01
            相关资源
            最近更新 更多