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:
- In your layout file, you assigned your TextView the ID
textView2. - But in your Activity code, you tried to fetch the view using
findViewById(R.id.textView). - Android generates a unique resource ID in the auto-generated
Rclass for every view that has an ID in your layouts. SinceR.id.textViewdoesn't correspond to any view in your actual layout,findViewById()returnsnullbecause it can't find a matching view. - When you called
setText(message)on thatnullTextView reference, it triggered ajava.lang.NullPointerException(wrapped in aRuntimeException), 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 benull(because it couldn't confirm the ID matched any view in your layout), so it highlighted thesetText()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
相关产品推荐
相关产品推荐

