IllegalArgumentException:指定为非null的参数为null

问题描述 投票:31回答:3

我收到以下运行时错误:

 checkParameterIsNotNull, parameter oneClickTokens
    at com.info.app.fragments.Fragment_Payment_Profile$fetchMerchantHashes$1.onPostExecute(Fragment_Payment_Profile.kt:0)
    at com.info.app.fragments.Fragment_Payment_Profile$fetchMerchantHashes$1.onPostExecute(Fragment_Payment_Profile.kt:1543)

这是我的代码:

 private fun fetchMerchantHashes(intent: Intent) {
    // now make the api call.
    val postParams = "merchant_key=$key&user_credentials=$var1"
    val baseActivityIntent = intent
    object : AsyncTask<Void, Void, HashMap<String, String>>() {

        override fun doInBackground(vararg params: Void): HashMap<String, String>? {
                ...
        }

        override fun onPostExecute(oneClickTokens: HashMap<String, String>) {
            super.onPostExecute(oneClickTokens)
            ...

        }
    }.execute()
}

似乎函数调用似乎无效。但是,我不知道如何解决这个问题。 Kotlin有什么具体的我错过了吗?

android exception null kotlin
3个回答
76
投票

例外情况非常明确:您正在为参数传递null

默认情况下,Kotlin中的所有变量和参数都是非空的。如果要将null参数传递给方法,则应将?添加到其类型中,例如:

fun fetchMerchantHashes(intent: Intent?)

有关更多信息:null-safety


1
投票

在我的情况下,此错误警告可能传递null作为参数。三种矫正方式。

  1. 更改相应位置的参数类型。如果是从Java接收的,请将@NonNull注释添加到变量定义中。
  2. !!添加到方法的参数中。
  3. ?添加到Kotlin类中的参数。我认为,Kotlin转换工具默认情况下可以这样做,如果在Java类中没有使用注释(如@Nullable@NonNull)。

0
投票

使用Android Studio转换工具将Activity从Java转换为Kotlin后,我发现了类似的异常。所以,我得到了override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent)

这是正确的override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)

intent: Intent?的差异


0
投票
Simple Answer Will Work For Sure...
When you are fetching the data from the Server using Rest Client (Web Services calls) (GET Or POST)

if there could be a null parameter value in the json response, and you are fetching the parameter and appending it to textview you get this error..

Solution:
just append ? mark to the variable as below..

   Example: 
        var batchNo: String? = "" (Correct Approach)

        var batchNo= "" (Will Get Error)

Here i am trying to fetch batchNo using service call....

...

Happy Coding @Ambilpura
© www.soinside.com 2019 - 2024. All rights reserved.