我有下面的代码
database.child("users").child(this.invitedBy).runTransaction(object : Transaction.Handler {
override fun doTransaction(mutableData: MutableData): Transaction.Result {
val u = mutableData.getValue(User::class.java)
?: return Transaction.success(mutableData)
if (u.numReferrals == null || u.referralEarning == null) {
// Unstar the post and remove self from stars
u.numReferrals = 1
u.referralEarning = 1;
} else {
// Star the post and add self to stars
u.numReferrals = u.numReferrals!! + 1
u.referralEarning = u.referralEarning!! + 1;
}
// Set value and report transaction success
mutableData.value = u
return Transaction.success(mutableData)
}
override fun onComplete(
databaseError: DatabaseError?,
committed: Boolean,
currentData: DataSnapshot?
) {
// Transaction completed
Log.d("MUser", "postTransaction:onComplete:" + databaseError!!)
}
})
当我运行它时,它给我以下错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.test, PID: 5375
kotlin.KotlinNullPointerException
at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database@@19.2.1:1006)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
W/System.err: kotlin.KotlinNullPointerException
W/System.err: at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database@@19.2.1:1006)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
这是我的用户.kt
import com.google.firebase.database.IgnoreExtraProperties
// [START rtdb_user_class]
@IgnoreExtraProperties
data class User(
var id: String = "",
var name: String = "",
var email: String = "",
var userReads: Int? = 0,
var userPlays: Int? = 0,
var userWatches: Int? = 0,
var paidDate : Int? = 0,
var endPaidDate : Int? = 0,
var paidStatus : String? = "",
var paymentMethod : String? = "",
var planid : String? = "",
var firebaseUid : String? = "",
var referralEarning : Int? = 0,
var numReferrals : Int? = 0
)
我做错了什么?
1条答案
按热度按时间8yparm6h1#
请看
onComplete
方法:引用
databaseError
参数时使用的是!!
运算符,但它可以为空,因此不能使用!!
。要避免该异常,只需删除!!
运算符:databaseError: DatabaseError?
-它是一个可空对象(用?
运算符标记的可空对象),如果不能100%确定它不是空的,则不能对其使用!!
运算符。您也可以在nullable对象上使用
?
运算子来呼叫其方法或属性,例如:More info about Null Safety in Kotlin。