简体   繁体   English

更改TextView的文本将引发NullPointer异常

[英]Changing text of a TextView throws NullPointer Exception

I'm just following the basic tutorial on the Android website. 我只是在遵循Android网站上的基本教程。 However, I'm trying to change a few things just for fun. 但是,我正在尝试为了娱乐而更改一些内容。 For instance, instead of creating a runtime TextView (as in the tutorial) within the method onCreate(...) of the DisplayMessageActivty class, I've defined a static TextView in the XML layout file because I'd like to show also other things (eg, a static message as well as the resulting entered message from the main screen). 例如,我没有在DisplayMessageActivty类的onCreate(...)方法中创建运行时TextView (如本教程中那样),而是在XML布局文件中定义了一个静态TextView ,因为我还想显示其他事物(例如,静态消息以及从主屏幕输入的结果消息)。 So, in the corresponding XML file of DisplayMessageActivty I've defined the TextView and other stuff as: 因此,在DisplayMessageActivty的相应XML文件中,我已将TextView和其他内容定义为:

[...]

<TextView android:id="@+id/dynamic_msg"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="ciao"
    android:textSize="40dp"
    android:layout_below="@id/static_msg"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/times" />

[...]

then, I access to that TextView in the following way ( onCreate(...) method of the DisplayMessageActivty class): 然后,我通过以下方式访问该TextViewDisplayMessageActivty类的onCreate(...)方法):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // HERE I WANT TO CHANGE THE CONTENT OF THE TEXTVIEW
    TextView dynamicText = (TextView) findViewById(R.id.dynamic_msg);
    dynamicText.setText(message);

    setContentView(R.layout.activity_display_message);

    // Up button
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Unfortunately, when I press the Send button in the main activity my code throws the following exception: 不幸的是,当我在主要活动中按“ Send按钮时,我的代码将引发以下异常:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

I've searched on the Internet and the approach adopted in other tutorials looks quite similar, so I cannot understand what I'm doing wrong. 我已经在Internet上进行搜索,其他教程中采用的方法看起来也很相似,所以我无法理解自己在做什么。 Thanks! 谢谢!

The content is not set into the view, the findviewByid will return NULL if you do it BEFORE setContentView . 内容未设置到视图中,如果在setContentView之前执行操作,则findviewByid将返回NULL。

move setContentView BEFORE findviewByid and it will work. setContentView findviewByid之前,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM