2016-06-21 5 views
10

私のアプリケーションをKotlinでコーディングしようとしていますが、nullを取得しようとしていますが、null以外の型にキャストできず、私がEXTRA_NOTEでEditNoteActivityを開くと、おそらく。kotlin.TypeCastException:nullをnull以外の型にキャストすることはできません。com.midsizemango.databasekotlin.Note

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([email protected], "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([email protected]) 
        .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([email protected], 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 
    } 
} 
} 

ログ:

java.lang.RuntimeException:活動ComponentInfo { com.midsizemango.databasekotlin/COMを開始することができません

任意のヘルプは非常に

コードを高く評価され.midsizemango.databasekotlin.EditNoteActivity}: kotlin.TypeCastException:nullをnull以外の型にキャストすることはできません com.mids android.app.ActivityThread.access $ 800(ActivityThreadで android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) でandroid.app.ActivityThread.performLaunchActivityでizemango.databasekotlin.Note (ActivityThread.java:2298)。 Javaの:144) android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)android.os.Looper.loopでandroid.os.Handler.dispatchMessage(Handler.java:102) で (ルーパーで.java:135)android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(ネイティブメソッド) at java.lang.re flect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:694)によって発生 :kotlin.TypeCastException:ヌル の非ヌル タイプcom.midsizemango.databasekotlin.Noteにキャストすることができないcom.midsizemango.databasekotlin.EditNoteActivity.onCreate(EditNoteActivity.kt:82) android.app.Activity.performCreate(Activity.java:5933) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)android.app.ActivityThread.access $ 800から で android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) (ActivityThread.java:144)で android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)android.os.Looper.loopでandroid.os.Handler.dispatchMessage(Handler.java:102) で (Looper.java:135で) android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(ネイティブメソッド)0 com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)com.android.internal.osで でjava.lang.reflect.Method.invoke(Method.java:372) で.ZygoteInit.main(ZygoteInit。Javaの:694)この行で

答えて

38

note = intent.getSerializableExtra(EXTRA_NOTE) as Note 

Notenon-null typeあるので、それへのキャストがnullチェックをトリガします。ただ、スウィフトのような

note = intent.getSerializableExtra(EXTRA_NOTE) as? Note 
+1

:式が右辺に指定されたタイプでない場合は、手動でその後nullnoteを比較しているので、おそらくあなたはnullを生み出すsafe cast operatorを意味しました! – Dante

+0

試してみてください –

+1

@Dante Kotlin初期リリース:2011、Swift初期リリース:2014年頃です。 – pablisco

関連する問題