主要活动:
val turminha : Turma = this.abrirArquivo()
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = AlunoAdapter(this,turminha.alunos)
floatingActionButton.setOnClickListener({
val i = Intent(this, ActivityAddAluno::class.java)
i.putExtra("turma", turminha)
startActivity(i)
})
ActivityAddAluno
class ActivityAddAluno : AppCompatActivity() {
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_aluno)
mBtnSalvarAluno.setOnClickListener{
var name = mEdtNomeAluno.text.toString()
var matricula = mEdtMatriculaAluno.text.toString()
toast("Nome: $name \n," +
"Matricula: $matricula")
turma.addAluno(Aluno(name, matricula))
}
}
Aluno班 Aluno类:Serializable {
var disciplinas: ArrayList<Disciplina>? = null
private set
var nome: String? = null
var matricula: String? = null
constructor() {
disciplinas = ArrayList()
}
constructor(nome: String, matricula: String) {
this.nome = nome
this.matricula = matricula
disciplinas = ArrayList()
}
类Turma
class Turma() : Serializable {
val alunos: ArrayList<Aluno>
init {
alunos = ArrayList()
}
fun addAluno(aluno: Aluno) {
alunos.add(aluno)
}
当我尝试访问在浮动按钮中传递我的Turma对象的其他活动时,应用程序停止工作。 Logcat说问题出在代码部分:
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
logcat的:
FATAL EXCEPTION: main
Process: com.example.thial.estudandokotlin, PID: 3428
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.thial.estudandokotlin/com.example.thial.estudandokotlin.ActivityAddAluno}:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
我该如何解决这个问题?
答案 0 :(得分:0)
实际上,根据您的日志消息,您的问题就在这里。
var i = getIntent()
private var turma = i.getSerializableExtra("turma") as Turma
此处值“i”为空,并且在此之上您尝试使用getSerializableExtra()
字符串。
您在ActivityAddAluno类中调用此行的确切位置是什么?它必须位于onCreate函数内,而不是在构造函数中。 (按照约书亚的说法)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//...
var i = getIntent()
if(i!=null)
{
private var turma = i.getSerializableExtra("turma") as Turma
}
}
以下是Switching between Activities along with data using Kotlin
示例之一