![](/img/trans.png)
[英]Well working Java code is causing kotlin.TypeCastException: null cannot be cast to non-null type when converted to Kotlin code
[英]Why do I receive “as non-null is null” error after Android Studio converts Java code into Kotlin code automatically?
当我将代码B(Java代码)复制并粘贴到Android Studio 3.1.2中时,我选择自动转换为Kotlin代码。
因此,我在Kotlin中获得了所示的代码A,但出现以下错误。 为什么?
当Android Studio自动将Java代码转换为Kotlin代码时,为什么会发生该错误?
顺便说一句,代码B(Java代码)效果很好。
错误
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter state
at ui.DialogChangePassword.showDialog(DialogChangePassword.kt)
代码A(科特林代码)
class DialogChangePassword(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs) {
private var mView: View? = null
init {
dialogLayoutResource = R.layout.item_custom_password_dialog
}
override fun onCreateDialogView(): View? {
// TODO Auto-generated method stub
mView = super.onCreateDialogView()
return mView
}
override fun onDialogClosed(positiveResult: Boolean) {
super.onDialogClosed(positiveResult)
}
override fun showDialog(state: Bundle) {
// Call show on default first so we can
// override the handlers
super.showDialog(state)
val d = dialog as AlertDialog
d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
if (IsInputOKAndSavePassword()) {
d.dismiss()
}
}
}
private fun IsInputOKAndSavePassword(): Boolean {
return true
}
}
代码B(Java代码)
public class DialogChangePassword extends DialogPreference {
private View mView;
public DialogChangePassword(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.item_custom_password_dialog);
}
@Override
protected View onCreateDialogView() {
// TODO Auto-generated method stub
mView = super.onCreateDialogView();
return mView;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
}
@Override
protected void showDialog(Bundle state) {
// Call show on default first so we can
// override the handlers
super.showDialog(state);
final AlertDialog d = (AlertDialog) getDialog();
d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (IsInputOKAndSavePassword()){
d.dismiss();
}
}
});
}
private boolean IsInputOKAndSavePassword(){
boolean result=true;
return result;
}
}
Kotlin通过区分可空类型(例如Bundle?
)和不可空类型(例如Bundle
)来将null
视为头等公民。
如您所知, Bundle
实例可以为空,具体取决于您当前处于组件生命周期的哪个阶段。例如,第一次创建Activity
实例时,将使用空Bundle
调用onCreate()
,因为没有状态要恢复。 如果由于配置更改而重新创建了相同的Activity
,则可以使用非null Bundle
实例(在其中可能存储了一些数据来帮助重新创建关联的屏幕)来调用onCreate()
)。
给定尽可能多的值, showDialog
签名应以允许state
可能为null的方式编写,如下所示:
override fun showDialog(state: Bundle?) {
...
}
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.