Android应用程序不断崩溃(Android studio)



我是编程新手。我正在构建一个简单的项目,通过单击按钮显示用户输入的数据。这款应用有时会在我按下按钮时启动并崩溃,有时会在立即打开后崩溃。这是我的XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextTextPersonName"
app:layout_constraintVertical_bias="0.003" />
<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:ems="10"
android:inputType="textPersonName"
android:scrollbars="vertical"
android:text="Name"
app:layout_constraintEnd_toStartOf="@+id/button"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

这是我的代码

package com.example.buttonclickapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private var textView: TextView? = null
private var button:Button? = null
private var userInput:EditText? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userInput = findViewById(R.id.editText)
button    = findViewById(R.id.button)
textView = findViewById(R.id.textView)
textView?.text = ""
textView?.movementMethod = ScrollingMovementMethod()
userInput?.setText ("")
button?.setOnClickListener(object : View.OnClickListener {
override fun onClick(p0: View?) {
textView?.append(userInput?.text)
textView?.append("n")
userInput?.text?.clear()

}
})

}
}

我是初学者,所以请简单解释

您的userInputfindViewById()错误的id。

修改userInput的findViewById如下:

userInput = findViewById(R.id.editTextTextPersonName)

如果你有更多的崩溃,复制logcat并发布到这里。

相关内容

最新更新