数据从Sql服务器获取并获取数据json。这个json数据解析retofit2。
创建了登录 Activity ,但给出错误

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>
}

最佳答案

产生NullPointerException的最可能原因是compositeDisposablenull

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

另外,应尽可能将val优先于var-因为不可变性更易于控制-且userNamepassword可能是局部变量,或者至少是private

关于kotlin - 改造给kotlin.KotlinNullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55743138/

10-10 09:36