照着敲代码总报错,八成不是你的问题,而是版本、依赖和细节没对上——这是无数 Android 编程实例教学中反复出现的坑。本文用一个完整可运行的「记账本」案例,从界面布局、事件绑定到 Room 数据存储,手把手拆解每一步,并附上报错对照表,零基础照做也能跑通自己的第一个 Android 编程实例。
照着敲总报错?先分清这四类根源
动手之前,先把最容易让人崩溃的四类错误说透。绝大多数“新手报错”,都能落进下面这张表里:
| 报错现象 | 常见根因 | 一句话解法 |
|---|---|---|
代码里满屏红色 Unresolved reference |
依赖没加,或加完没同步 Gradle | 点右上角「Sync Project with Gradle Files」 |
Cannot access database on the main thread |
数据库操作写在了主线程 | 用协程 lifecycleScope.launch 包起来 |
NullPointerException 指向 findViewById 返回值 |
布局里的 ID 拼错,或忘了 setContentView |
核对 @+id/xxx 和 R.id.xxx 是否一致 |
新建项目后找不到 activity_main.xml |
模板选成了 Compose 的 Empty Activity | 新建时选「Empty Views Activity」 |
还有一个更隐蔽的原因:IDE 版本和教程版本对不上。两年前的教程写的可能是 android.support 旧包名,现在早就迁移到 androidx 了。抄旧代码时,import 语句一定要全部删掉重新自动导入,别照抄。
案例怎么选:零基础第一个项目做什么
很多人的第一个项目选了天气 API、股票接口这类需要联网和解析 JSON 的案例,结果卡在权限配置和乱码问题上,热情直接耗光。我的建议是选纯本地、不联网、数据量小的案例,比如记账本、待办清单、密码本。记账本的好处是:界面只有输入框加按钮,数据有明确结构(金额、备注、时间),天然需要列表展示和数据存储,正好把界面、逻辑、持久化三块全走一遍。
时间预算上,按本文步骤完整敲一遍大约需要 2~3 小时(含调试),跑通之后你会对 Android 的基本开发流程有完整认知。
第一步:新建项目与界面布局
在 Android Studio 里点 New Project,选 Empty Views Activity(注意不是 Empty Activity,后者用的是 Jetpack Compose,没有 XML 布局文件),语言选 Kotlin,Minimum SDK 选 API 24 即可,然后 Finish。
布局文件在 app/src/main/res/layout/activity_main.xml,把内容替换成下面这段。用的是最基础的 LinearLayout 纵向排列,零基础只需要搞懂三个属性:layout_width/layout_height 决定控件占多大,orientation 决定横排还是竖排,padding 是内边距。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/amountEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入金额,例如 25.5"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/remarkEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="备注,例如 午饭"
android:layout_marginTop="8dp" />
<Button
android:id="@+id/addButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="记一笔"
android:layout_marginTop="12dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="12dp" />
</LinearLayout>
敲这段 XML 时最常见的两个坑:一是属性名打错(比如把 layout_width 写成 layout_wdith),XML 不报错但控件显示异常;二是 EditText 的 inputType 写错,输入法行为会变。出现奇怪现象时,第一反应应该是回查 XML,而不是改 Kotlin 代码。
第二步:绑定事件与业务逻辑
界面有了,接下来让按钮「活」起来。打开 MainActivity.kt,先写一个最简版本,把数据打印到日志里验证逻辑通不通:
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val amountEdit = findViewById<EditText>(R.id.amountEdit)
val remarkEdit = findViewById<EditText>(R.id.remarkEdit)
val addButton = findViewById<Button>(R.id.addButton)
addButton.setOnClickListener {
val amount = amountEdit.text.toString().toDoubleOrNull() ?: 0.0
val remark = remarkEdit.text.toString().ifEmpty { "无备注" }
Log.d("MoneyApp", "记账:$amount 元,$remark")
}
}
}
逐段解释:setContentView 负责把 XML 布局挂到屏幕上,漏掉这行,后面所有 findViewById 都会返回 null,这是新手 NullPointerException 的头号来源。findViewById 的含义是「按 ID 在当前布局里找控件」,泛型 <EditText> 告诉编译器它的类型。setOnClickListener 里写的是点击按钮后执行的代码。toDoubleOrNull() 比 toDouble() 安全——用户输入为空时不会崩溃,而是返回 null,我们用 ?: 0.0 兜底。
到这里先运行一次:点按钮,看 Logcat 里有没有输出。养成这个习惯——每写完一小块就运行一次,报错时问题范围小,排查成本远低于全部敲完再跑。
第三步:数据存储——用 Room 把账目真正存下来
Room 是指 Android 官方 Jetpack 组件中的关系型数据库框架,它把底层的 SQLite 封装成面向对象的数据库访问接口,是目前 Android 上做本地数据存储的首选方案。 它分三层:Entity(表结构定义)、DAO(增删改查接口)、Database(数据库入口)。敲代码前记得先在 app/build.gradle.kts 的 dependencies 里加依赖,然后点 Sync:
dependencies {
implementation("androidx.room:room-runtime:2.6.1")
implementation("androidx.room:room-ktx:2.6.1")
kapt("androidx.room:room-compiler:2.6.1")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.0")
implementation("androidx.recyclerview:recyclerview:1.3.2")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.4")
}
同时确认 plugins 块里有 id("kotlin-kapt")——少了它,Room 的注解处理器不生效,编译直接报找不到生成的实现类,这是 Room 案例里最高频的报错。
1. 定义表结构(Entity):新建 Record.kt:
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "records")
data class Record(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val amount: Double,
val remark: String,
val date: String
)
@PrimaryKey(autoGenerate = true) 表示主键自增,你不用手动编号,插入时传 id = 0 就行。2. 定义增删改查接口(DAO):新建 RecordDao.kt:
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface RecordDao {
@Insert
suspend fun insert(record: Record)
@Query("SELECT * FROM records ORDER BY id DESC")
fun getAll(): Flow<List<Record>>
}
@Query 里写的就是 SQL 语句,注意表名必须和 Entity 的 tableName 一字不差。返回值用 Flow 是为了让数据变化时列表自动刷新。3. 数据库入口:新建 AppDatabase.kt:
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Record::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun recordDao(): RecordDao
}
第四步:列表展示与完整串联
新建 item_record.xml,这是列表里每一行的样子:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<TextView
android:id="@+id/amountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#0A7C3F"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/remarkText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="12dp"
android:textSize="14sp" />
</LinearLayout>
然后是适配器 RecordAdapter.kt,它负责把一条条数据「贴」到一行行界面上:
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class RecordAdapter(private val records: List<Record>) :
RecyclerView.Adapter<RecordAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val amountText: TextView = view.findViewById(R.id.amountText)
val remarkText: TextView = view.findViewById(R.id.remarkText)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_record, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val record = records[position]
holder.amountText.text = "¥${record.amount}"
holder.remarkText.text = "${record.remark} · ${record.date}"
}
override fun getItemCount() = records.size
}
最后把 MainActivity.kt 升级为完整版:
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class MainActivity : AppCompatActivity() {
private lateinit var dao: RecordDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val db = Room.databaseBuilder(
applicationContext, AppDatabase::class.java, "money.db"
).build()
dao = db.recordDao()
val amountEdit = findViewById<EditText>(R.id.amountEdit)
val remarkEdit = findViewById<EditText>(R.id.remarkEdit)
val addButton = findViewById<Button>(R.id.addButton)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
addButton.setOnClickListener {
val amount = amountEdit.text.toString().toDoubleOrNull() ?: 0.0
val remark = remarkEdit.text.toString().ifEmpty { "无备注" }
val date = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
.format(Date())
lifecycleScope.launch {
dao.insert(Record(amount = amount, remark = remark, date = date))
loadRecords()
}
}
loadRecords()
}
private fun loadRecords() {
lifecycleScope.launch {
dao.getAll().collect { list ->
recyclerView.adapter = RecordAdapter(list)
}
}
}
}
两个关键点:dao.insert 必须包在 lifecycleScope.launch 里,否则就是前面说的「不能在主线程访问数据库」报错;dao.getAll().collect 监听数据流,每次插入新记录,列表会自动刷新,不用手动通知适配器。运行后输入金额点按钮,列表出现记录,重启 App 数据还在——这就完成了一次从界面到存储的完整闭环。
敲代码时的报错对照表
| 你看到的报错 | 真实原因 | 处理方式 |
|---|---|---|
Unresolved reference: Room |
依赖未加或未 Sync | 核对依赖版本,点 Sync |
编译报找不到 RecordDao_Impl |
没加 kotlin-kapt 插件 |
plugins 块补上后重新 Sync |
Cannot access database on the main thread |
数据库操作在主线程 | 用 lifecycleScope.launch 包裹 |
Attempt to invoke on a null object |
findViewById 的 ID 拼错 |
比对 XML 的 @+id 与代码 R.id |
| Logcat 空白无输出 | 过滤条件选错了进程 | Logcat 左侧选对设备与进程 |
INSTALL_FAILED_USER_RESTRICTED 等安装失败 |
手机未开启 USB 调试或驱动异常 | 开发者选项里勾选 USB 调试,重插数据线 |
一个实用建议:看 Logcat 时先找第一个红色异常,而不是最后一行。Android 的异常链通常是第一个错误引发后面一片连锁报错,源头往往在它上面。
从能跑到写得好的三个进阶建议
跑通之后,别急着做下一个大项目,先把地基夯实:一是把 findViewById 换成 ViewBinding,减少大量样板代码和 null 风险;二是给数据加一张「删除」功能,练习 @Delete 注解和 Snackbar 交互;三是把金额字段从 Double 换成以「分」为单位的 Long,这是真实金融类 App 的通用做法,避免浮点精度问题。这三步做完,你就已经超过大多数只看视频不动手的初学者了。
常见问题
零基础学 Android 需要先学什么?
只需要三样:Kotlin 基础语法(变量、函数、类)、XML 布局的基本属性、对 Android Studio 的基本操作。会写「Hello World」级别的 Kotlin 就够了,剩下的是在项目里边做边补,不需要先啃完整本语法书。
用 Java 还是 Kotlin?
做新项目一律选 Kotlin。官方已默认 Kotlin,现有 Java 教程大多是 2019 年前的旧资料,包名、依赖写法都有差异,照着抄更容易踩坑。
这个案例要写多久?
熟悉步骤后 2~3 小时可跑通;零基础第一次做,加上读代码和调试,建议预留半天,每完成一步运行一次,效率最高。
报错日志看不懂怎么办?
先复制完整报错,搜第一个异常类名(如 IllegalStateException),90% 的报错是高频老问题,搜到的答案里通常直接给出原因和改法。实在不行,把异常信息连同代码一起描述给 AI 助手,它能准确定位到行。
数据存在哪里,卸载 App 会丢吗?
Room 底层是 SQLite,数据文件存在手机应用专属目录(/data/data/包名/databases/)里,卸载 App 会连同数据一起删除,所以涉及重要数据的应用要另外考虑云端同步。