改造给kotlin.KotlinNullPointerException

时间:2019-04-18 09:32:48

标签: kotlin retrofit2

从Sql服务器获取数据并获取数据json。这个json数据解析retofit2。  创建了登录活动,但输入错误

MainActivity.kt

class MainActivity : AppCompatActivity() {


    internal lateinit var api : APIInterface

    private var compositeDisposable : CompositeDisposable? = null

    var userName : String? = null

    var password : String? = null

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

        btnLogin.setOnClickListener {

            userName = tvUsername.text.toString()
            password = tvPassword.text.toString()

            getUserName(userName!!,password!!)
        }
    }

    fun getUserName(user : String, pass : String){


        val retrofit = APIClient.apIClient
        if (retrofit != null) {
            api = retrofit.create(APIInterface::class.java)
        }
        compositeDisposable!!.add(api.getLoginData(user, pass)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.success.equals(1)){

                    val intent = Intent(this,Company::class.java)
                    startActivity(intent)

                    Toast.makeText(this,"Login Successfully!!!",Toast.LENGTH_LONG).show()
                }else{

                    Toast.makeText(this,"UserName or Password is Wrong!!!",Toast.LENGTH_LONG).show()
                }
                },{
                    Toast.makeText(this, it.message, Toast.LENGTH_LONG).show()
                })
        )
    }
}

当Debbuger到达CompositeDisposable !!。add(api.getLoginData(user,pass)时,会给出错误kotlin.kotlinNullPointerException

RestApi网址:

http://localhost/Account/Login.php?user=ABC&pass=1

APIClient.kt

object APIClient {
   val BASE_URL = "http://10.0.2.2/Account/"
    var retrofit:Retrofit? = null
    val apIClient:Retrofit?
        get() {
            if (retrofit == null)
            {
                retrofit =  Retrofit.Builder().
                        baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build()
            }
            return retrofit
        }


}

APIInterface.kt

interface APIInterface {
 @GET("Login.php")
    fun getLoginData(@Query("user") user : String,
                     @Query("pass") pass : String) : Observable<LoginList>
}

1 个答案:

答案 0 :(得分:1)

NullPointerException最可能的原因是compositeDisposablenull

MyActivity的开头,该变量被初始化为null,并且从未更改,因此,当您使用!!运算符时,将引发异常。 我认为您可以直接使用正确的值compositeDisposable初始化val compositeDisposable = CompositeDisposable()

此外,val应该比var优先(因为不变性更易于控制),并且userNamepassword可能是局部变量,或者至少是{ {1}}