【问题标题】:Android Change text in TextViewAndroid 更改 TextView 中的文本
【发布时间】:2015-10-14 22:59:12
【问题描述】:

我正在尝试使用 setText() 更改 TextView 中的文本。

当我尝试这样做时,我收到以下错误:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{<bla bla bla>}: java.lang.NullPointerException

Caused by: java.lang.NullPointerException
            at com.training.mytraining.test.MainActivity.display(MainActivity.java:35)

MainActivity.java

public class MainActivity extends AppCompatActivity {
TextView tvCountry;
private Server theServer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvCountry = (TextView) findViewById(R.id.countryTextView);


    theServer = new Server(this);
    theServer.weatherFromYahoo();


}


public void display() {

    tvCountry.setText("USA");
}


}

Server.java

public class Server extends AppCompatActivity {
MainActivity theMainActivity;

//Constructor
public Server (Context context){
    this.theMainActivity = new MainActivity();
}

public void weatherFromYahoo() {

    theMainActivity.display();
}

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
    android:id="@+id/countryTextView"
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

这只是我真实代码的一个例子。我不想放所有代码,所以我用我遇到的那个问题制作了一个新代码。我必须通过从另一个类调用我的 MainActivity 来设置文本。

请帮帮我,我已经卡在这里几个小时了。

【问题讨论】:

标签: java android nullpointerexception textview settext


【解决方案1】:

改变这个:

public Server (Context context){
    this.theMainActivity = new MainActivity();
}

到这里:

public Server (Context context){
    this.theMainActivity = (MainActivity)context;
}

这样 onCreate 仍然被正确调用。如果您正在新建一个活动,它将无法正确设置视图并遵循正确的生命周期。正如@CommonsWare 所说,您永远不应该通过其构造函数创建活动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2019-04-13
    • 2015-07-05
    • 2014-02-07
    • 1970-01-01
    相关资源
    最近更新 更多