J'essaie de coder mon application dans Kotlin, mais j'obtiens une valeur null qui ne peut pas être convertie en un type non nul et l'application s'arrête lorsque j'ouvre EditNoteActivity à EXTRA_NOTE probablement.
Toute aide est grandement appréciée
Code:
class EditNoteActivity : AppCompatActivity() {
var note: Note? = null
private val editNote: TextView? = null
private val fabdrwble: Boolean? = null
private val notesData: MutableList<Note>? = null
private var databaseHelper: DatabaseHelper? = null
private val save: Boolean? = null
private var saveButton: FloatingActionButton? = null
private val tint: ColorStateList? = null
internal var mRowId: Long? = null
internal var spinner: Spinner? = null
internal var spinnertext: String? = null
internal var fav: Int = 0
internal var mSharedFromIntentFilter = false
internal var editTitle: EditText? = null
internal var editContent: EditText? = null
internal var inputlayoutTitle: TextInputLayout? = null
internal var inputlayoutContent: TextInputLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_note)
var toolbar = findViewById(R.id.toolbar_edit) as Toolbar?
setSupportActionBar(toolbar)
if (supportActionBar != null)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
databaseHelper = DatabaseHelper(applicationContext)
inputlayoutTitle = findViewById(R.id.inputlayoutTitle) as TextInputLayout?
inputlayoutContent = findViewById(R.id.inputlayoutContent) as TextInputLayout?
editTitle = findViewById(R.id.note_title) as EditText
editContent = findViewById(R.id.note_content) as EditText?
val bundle = intent.extras
val s = bundle.getString("edit")
if (s == "add") {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
} else if (s == "editv") {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
}
note = intent.getSerializableExtra(EXTRA_NOTE) as Note
if (note != null) {
editTitle?.setText(note!!.getTitle())
editContent?.setText(note!!.getContent())
} else {
note = Note()
//note.setUpdatedAt(new Date());
}
saveButton = findViewById(R.id.add_edit_button) as FloatingActionButton?
saveButton!!.setOnClickListener {
if (isNoteFormOk) {
setNoteResult()
finish()
} else
validateNoteForm()
}
var ll = findViewById(R.id.llmain) as LinearLayout?
var ll1 = findViewById(R.id.ll1) as LinearLayout?
/*if(note.getColor() == Color.TRANSPARENT){
selectedColor = preselect;
}else {
selectedColor = note.getColor();
}
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
systemBarTintManager = new SystemBarTintManager(this);
systemBarTintManager.setStatusBarTintEnabled(true);
ll.setBackgroundColor(selectedColor);
ll1.setBackgroundColor(selectedColor);
toolbar.setBackgroundColor(note.getColor());
systemBarTintManager.setStatusBarTintColor(selectedColor);*/
}
override fun onResume() {
super.onResume()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
Android.R.id.home -> {
onBack()
return true
}
/*
case R.id.speech:
try {
displaySpeechRecognizer();
} catch (ActivityNotFoundException e) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://market.Android.com/details?id=com.google.Android.googlequicksearchbox"));
startActivity(browserIntent);
}
return true;*/
else -> return super.onOptionsItemSelected(item)
}
}
private fun displaySpeechRecognizer() {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
startActivityForResult(intent, SPEECH_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int,
data: Intent) {
if (requestCode == SPEECH_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
val spokenText = results[0]
editContent?.setText(spokenText)
}
if (requestCode == RequestResultCode.REQUEST_CODE_ADD_NOTE) {
if (resultCode == Activity.RESULT_OK) {
addNote(data)
}
}
}
private val isNoteFormOk: Boolean
get() {
val title = editTitle?.text.toString()
return !(title == null || title.trim { it <= ' ' }.length == 0)
}
private fun validateNoteForm() {
var msg: String? = null
if (isNullOrBlank(editTitle?.text.toString())) {
msg = "Title Required"
inputlayoutTitle?.error = "Title is Missing"
}
if (msg != null) {
Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG).show()
}
}
private fun setNoteResult() {
note!!.setTitle(editTitle?.text.toString().trim { it <= ' ' })
note!!.setContent(editContent?.text.toString().trim { it <= ' ' })
//note.setUpdatedAt(new Date());
val intent = Intent()
intent.putExtra(EXTRA_NOTE, note)
setResult(Activity.RESULT_OK, intent)
//addNote(intent);
Toast.makeText(this@EditNoteActivity, "Note Saved.", Toast.LENGTH_LONG).show()
}
private fun onBack() {
if (isNoteFormOk) {
if (editTitle?.text.toString() == note!!.getTitle() && editContent?.text.toString() == note!!.getContent()) {
setResult(Activity.RESULT_CANCELED, Intent())
finish()
} else {
AlertDialog.Builder(this@EditNoteActivity)
.setTitle("Save")
.setMessage("Do You Want to Save Note")
.setPositiveButton("SAVE") { dialog, which ->
setNoteResult()
finish()
}.setNegativeButton("CANCEL") { dialog, which ->
setResult(Activity.RESULT_CANCELED, Intent())
finish()
}.show()
}
} else {
setResult(Activity.RESULT_CANCELED, Intent())
finish()
}
}
private fun addNote(data: Intent) {
val note = data.getSerializableExtra(EXTRA_NOTE) as Note
val noteId = databaseHelper!!.createNote(note)
note.setId(noteId)
}
override fun onBackPressed() {
onBack()
val intentHome = Intent(this@EditNoteActivity, MainActivity::class.Java)
intentHome.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intentHome.putExtra(EXTRA_NOTE, note)
setResult(Activity.RESULT_OK, intentHome)
}
companion object {
private val EXTRA_NOTE = "EXTRA_NOTE"
private val SPEECH_REQUEST_CODE = 0
fun isNullOrBlank(str: String?): Boolean {
return str == null || str.trim { it <= ' ' }.length == 0
}
}
}
Journaux:
Java.lang.RuntimeException: Impossible de démarrer l'activité ComponentInfo {com.midsizemango.databasekotlin/com.midsizemango.databasekotlin.EditNoteActivity}: kotlin.TypeCastException: la valeur null ne peut pas être convertie en type non nul com.midsizemango.databasek.Note à Android. app.ActivityThread.performLaunchActivity (ActivityThread.Java:2298) à Android.app.ActivityThread.handleLaunchActivity (ActivityThread.Java:2360) à Android.app.ActivityThread.access $ 800 (ActivityThread.Java:144) à Android.app.ActivityThread $ H.handleMessage (ActivityThread.Java:1278) sur Android.os.Handler.dispatchMessage (Handler.Java:102) sur Android.os.Looper.loop (Looper.Java:135) sur Android.app.ActivityThread.main (ActivityThread .Java: 5221) à Java.lang.reflect.Method.invoke (Méthode native) à Java.lang.reflect.Method.invoke (Method.Java:372) à com.Android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.Java:899) sur com.Android.internal.os.ZygoteInit.main (ZygoteInit.Java:694) Causée par: kotlin.TypeCastException: null ne peut pas être converti en un type non nul com.midsizemango.databasekotlin.Note à com.midsizemango.databasekotlin.EditNoteActivity.onCreate (EditNoteActivity.kt: 82) sur Android.app.Activity.performCreate (Activity.Java:5933) sur Android.app .Instrumentation.callActivityOnCreate (Instrumentation.Java:1105) sur Android.app.ActivityThread.performLaunchActivity (ActivityThread.Java:2251) sur Android.app.ActivityThread.handleLaunchActivity (ActivityThread.Java:2251) sur Android.app.ActivityThread.handleLaunchActivity (ActivityThread.Java:60. (ActivityThread.Java:144) sur Android.app.ActivityThread $ H.handleMessage (ActivityThread.Java:1278) sur Android.os.Handler.dispatchMessage (Handler.Java:102) sur Android.os.Looper.loop (Looper. Java: 135) sur Android.app.ActivityThread.main (ActivityThread.Java:5221) sur Java.lang.reflect.Method.invoke (Méthode native) sur Java.lang.reflect.Method.invoke (Method.Java:372) sur com.Android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.Java:899) sur com.Android.internal.os.ZygoteInit.main (ZygoteInit.Java : 694)
Dans cette ligne:
note = intent.getSerializableExtra(EXTRA_NOTE) as Note
Note
est un type non-nul , ainsi le transfert qui en découle déclenche une vérification nulle. Puisque vous comparez ensuite note
à null
manuellement, vous vouliez probablement dire opérateur de casting sécurisé , ce qui donne null
si l'expression n'est pas de le type spécifié dans le côté droit:
note = intent.getSerializableExtra(EXTRA_NOTE) as? Note