You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android入门项目DisplayMessageActivity启动崩溃及setText异常求助

Why Your DisplayMessageActivity Crashed & the Fix Explained

Hey there, let's break down exactly what caused your crash and why tweaking the view ID solved it—this is one of the most common pitfalls for new Android developers!

The Core Issue: Mismatched View IDs

Your crash boiled down to a simple mismatch between the ID in your code and the ID in your layout XML:

  1. In your layout file, you assigned your TextView the ID textView2.
  2. But in your Activity code, you tried to fetch the view using findViewById(R.id.textView).
  3. Android generates a unique resource ID in the auto-generated R class for every view that has an ID in your layouts. Since R.id.textView doesn't correspond to any view in your actual layout, findViewById() returns null because it can't find a matching view.
  4. When you called setText(message) on that null TextView reference, it triggered a java.lang.NullPointerException (wrapped in a RuntimeException), which caused your app to crash the second the activity launched.

Those IDE Quirks You Noticed, Explained

  • Manual setText() turning red: Android Studio was giving you a proactive warning! It detected that the TextView reference might be null (because it couldn't confirm the ID matched any view in your layout), so it highlighted the setText() call as a potential null pointer risk.
  • Copied tutorial code showing setText() as gray: The tutorial's code was written to match their layout's ID (textView). Since your layout used a different ID, the IDE might not have immediately caught the mismatch (maybe due to resource caching or delayed sync), but the underlying problem was still present—your code was still trying to access a non-existent view.

Why Changing the ID Fixed Everything

Once you updated your code to use findViewById(R.id.textView2), the method could correctly locate the TextView in your layout. It returned a valid, non-null reference, so calling setText(message) worked as intended, and your activity launched without crashing.

内容的提问来源于stack exchange,提问作者Amirates

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:50:29