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

时间:2017-07-03 12:36:34

标签: android exception null kotlin

我收到以下运行时错误

 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有什么具体的我错过了吗?

5 个答案:

答案 0 :(得分:71)

异常非常清楚:您正在为null传递参数。

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

fun fetchMerchantHashes(intent: Intent?)

有关详细信息:null-safety

答案 1 :(得分:1)

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

  1. 更改相应位置的参数类型。如果从Java收到,请将@NonNull注释添加到变量定义中。
  2. !!添加到方法的参数中。
  3. ?添加到Kotlin类中的参数。我认为,如果在Java类中没有使用注释(例如@Nullable@NonNull),Kotlin转换工具可能会默认执行此操作。

答案 2 :(得分: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?

中的差异

答案 3 :(得分: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

答案 4 :(得分:0)

对于每个绑定适配器,将 item 参数的类型更改为 nullable,并用

包裹主体 <块引用>

item?.let{...}

source 在 Google 文档中