在安卓中为TextView设置值

4
如何给TextView赋值?
<TextView
    android:id="@+id/hName"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:textSize="25sp" 
    android:text = "@string/hName"/>

<LinearLayout 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

这是我正在创建的一个视图的结构。现在,我想将来自上一个活动的值分配给hname。我能够从上一个活动中获取它,但我无法将其设置为textview。当我使用setText()时,它显示空指针异常。如何将值分配给该文本字段。先感谢您。
这是相应的java代码。
    Intent intent = getIntent();
    String host_name = intent.getStringExtra(ConnectionsActivity.HOST_NAME);
    TextView tvName = (TextView)findViewById(R.id.hName);
    tvName.setText(host_name);
    setContentView(R.layout.sharedfiles);

不清楚:hname 属于上一个活动? - Phantômaxx
几乎可以确定findViewById返回了null,这意味着您使用了错误的id或在设置内容视图之前调用它,或者根本忘记调用它。 - Gabe Sechan
2
将setContentView(R.layout.sharedfiles);移到顶部 - Apoorv
我已经尝试过了。它显示相同的错误。错误在setText行中。如果我注释掉那一行,就不会显示任何错误。我认为tvName为空。 - user3453575
请发布您之前的startActivity方法。您确定之前的活动将该EXTRA添加到意图中吗? - Vikrant_Dev
2个回答

4

你的结构存在问题。

它会抛出 null-pointer 异常,因为找不到文本视图...

setContentView(R.layout.sharedfiles); 放在 intent 上面...

试试这个方法...

setContentView(R.layout.sharedfiles);
Intent intent = getIntent();
String host_name = intent.getStringExtra(ConnectionsActivity.HOST_NAME);
TextView tvName = (TextView)findViewById(R.id.hName);
tvName.setText(host_name);

0

@string/hName 可以在你应用程序的任何代码中访问

getString(R.string.hName);

空指针异常来自其他地方,你最好发布你的logcat。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接